file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20 {
using SafeMath for uint256;
mapping (address => uint256) private balances;
mapping (address => mapping (address => uint256)) private allowed;
uint256 private totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @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) {
return balances[_owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _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 returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _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
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 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;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param _account The account that will receive the created tokens.
* @param _amount The amount that will be created.
*/
function _mint(address _account, uint256 _amount) internal {
require(_account != 0);
totalSupply_ = totalSupply_.add(_amount);
balances[_account] = balances[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param _account The account whose tokens will be burnt.
* @param _amount The amount that will be burnt.
*/
function _burn(address _account, uint256 _amount) internal {
require(_account != 0);
require(_amount <= balances[_account]);
totalSupply_ = totalSupply_.sub(_amount);
balances[_account] = balances[_account].sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal _burn function.
* @param _account The account whose tokens will be burnt.
* @param _amount The amount that will be burnt.
*/
function _burnFrom(address _account, uint256 _amount) internal {
require(_amount <= allowed[_account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
allowed[_account][msg.sender] = allowed[_account][msg.sender].sub(_amount);
_burn(_account, _amount);
}
}
/**
* @title FasTrader Token
*/
contract FasTrader is StandardToken {
string public constant name = "FasTrader";
string public constant symbol = "FTD";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 100000000000 * (10 ** uint256(decimals));
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
_mint(msg.sender, INITIAL_SUPPLY);
}
} | * @dev Total number of tokens in existence/ | function totalSupply() public view returns (uint256) {
return totalSupply_;
}
| 176,275 | [
1,
5269,
1300,
434,
2430,
316,
15782,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
2078,
3088,
1283,
67,
31,
203,
282,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0x717955905bf71b84651f4eD75AAC4C6A4b33b410/sources/contracts/LB/libraries/Math512Bits.sol | @notice Helper function to return the result of `x * y / denominator` with full precision @param x The multiplicand as an uint256 @param y The multiplier as an uint256 @param denominator The divisor as an uint256 @param prod0 The least significant 256 bits of the product @param prod1 The most significant 256 bits of the product @return result The result as an uint256 Handle non-overflow cases, 256 by 256 division Compute remainder using mulmod. Subtract 256 bit number from 512 bit number. Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1 See https:cs.stackexchange.com/q/138556/92363 Does not overflow because the denominator cannot be zero at this stage in the function Divide denominator by lpotdod. Divide [prod1 prod0] by lpotdod. Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one | function _getEndOfDivRoundDown(
uint256 x,
uint256 y,
uint256 denominator,
uint256 prod0,
uint256 prod1
) private pure returns (uint256 result) {
if (prod1 == 0) {
unchecked {
result = prod0 / denominator;
}
assembly {
remainder := mulmod(x, y, denominator)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
unchecked {
uint256 lpotdod = denominator & (~denominator + 1);
assembly {
denominator := div(denominator, lpotdod)
prod0 := div(prod0, lpotdod)
lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
}
}
}
| 4,624,793 | [
1,
2276,
445,
358,
327,
326,
563,
434,
1375,
92,
225,
677,
342,
15030,
68,
598,
1983,
6039,
225,
619,
1021,
3309,
1780,
464,
487,
392,
2254,
5034,
225,
677,
1021,
15027,
487,
392,
2254,
5034,
225,
15030,
1021,
15013,
487,
392,
2254,
5034,
225,
10791,
20,
1021,
4520,
14177,
8303,
4125,
434,
326,
3017,
225,
10791,
21,
1021,
4486,
14177,
8303,
4125,
434,
326,
3017,
327,
563,
1021,
563,
487,
392,
2254,
5034,
5004,
1661,
17,
11512,
6088,
16,
8303,
635,
8303,
16536,
8155,
10022,
1450,
14064,
1711,
18,
2592,
1575,
8303,
2831,
1300,
628,
13908,
2831,
1300,
18,
26400,
7602,
414,
434,
2795,
596,
434,
15030,
471,
3671,
12756,
7212,
434,
2795,
15013,
434,
15030,
18,
14178,
1545,
404,
2164,
2333,
30,
2143,
18,
3772,
16641,
18,
832,
19,
85,
19,
26645,
2539,
26,
19,
29,
4366,
4449,
9637,
486,
9391,
2724,
326,
15030,
2780,
506,
3634,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
389,
588,
23358,
7244,
11066,
4164,
12,
203,
3639,
2254,
5034,
619,
16,
203,
3639,
2254,
5034,
677,
16,
203,
3639,
2254,
5034,
15030,
16,
203,
3639,
2254,
5034,
10791,
20,
16,
203,
3639,
2254,
5034,
10791,
21,
203,
565,
262,
3238,
16618,
1135,
261,
11890,
5034,
563,
13,
288,
203,
3639,
309,
261,
17672,
21,
422,
374,
13,
288,
203,
5411,
22893,
288,
203,
7734,
563,
273,
10791,
20,
342,
15030,
31,
203,
5411,
289,
203,
203,
5411,
19931,
288,
203,
7734,
10022,
519,
14064,
1711,
12,
92,
16,
677,
16,
15030,
13,
203,
203,
7734,
10791,
21,
519,
720,
12,
17672,
21,
16,
9879,
12,
2764,
25407,
16,
10791,
20,
3719,
203,
7734,
10791,
20,
519,
720,
12,
17672,
20,
16,
10022,
13,
203,
5411,
289,
203,
203,
5411,
22893,
288,
203,
7734,
2254,
5034,
12423,
352,
72,
369,
273,
15030,
473,
261,
98,
13002,
26721,
397,
404,
1769,
203,
7734,
19931,
288,
203,
10792,
15030,
519,
3739,
12,
13002,
26721,
16,
12423,
352,
72,
369,
13,
203,
203,
10792,
10791,
20,
519,
3739,
12,
17672,
20,
16,
12423,
352,
72,
369,
13,
203,
203,
10792,
12423,
352,
72,
369,
519,
527,
12,
2892,
12,
1717,
12,
20,
16,
12423,
352,
72,
369,
3631,
12423,
352,
72,
369,
3631,
404,
13,
203,
7734,
289,
203,
203,
203,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/// @title EmergencyStop: A circuit breaker for temporarily disabling contract functions
/// @author John McCrae
/// @dev This contract requires solidity compiler version 0.5 or higher
pragma solidity ^0.5.0;
/// @dev EmergencyStop: A contract that implements the circuit breaker design pattern
contract EmergencyStop {
/// @param ownerESC A public payable address data type
address payable public ownerESC;
/// @param emergencyStopSwitch A public boolean data type to keep track of emergencyStopSwitch (circuit breaker flag)
bool public emergencyStopSwitch;
/// @param _emergencySwitchValue A boolean data type to keep track of changes to emergencyStopSwitch
event LogEmergencyStopSwitch(bool _emergencySwitchValue);
/// @dev verifyOwnerESC A modifier requiring the message sender address is equal to the owner address
modifier verifyOwnerESC () {
require(ownerESC == msg.sender, "Access denied. Access restricted to contract owner.");
_;
}
/// @dev verifyEmergencyStopValue A modifier requiring emergencyStopSwitch (circuit breaker flag) to be false
modifier verifyEmergencyStopValue () {
require(emergencyStopSwitch == false, "Access denied. This contract has been temporarily disabled.");
_;
}
/// @dev Declare constructor. Set ownerESC to be the contract creator.
constructor () public {
ownerESC = msg.sender;
}
/// @dev emergencyStopFunction() A function that allows setting emergencyStopSwitch (circuit breaker flag) to true or false
/// @param emergencySwitchValue A boolean data type for changing the state of emergencyStopSwitch (circuit breaker flag)
/// @return A boolean data type returning the new value of emergencyStopSwitch (circuit breaker flag)
function emergencyStopFunction (bool emergencySwitchValue)
public
verifyOwnerESC
returns(bool _emergencyStopSwitch)
{
emit LogEmergencyStopSwitch(emergencySwitchValue);
emergencyStopSwitch = emergencySwitchValue;
return emergencyStopSwitch;
}
} | @dev emergencyStopFunction() A function that allows setting emergencyStopSwitch (circuit breaker flag) to true or false @param emergencySwitchValue A boolean data type for changing the state of emergencyStopSwitch (circuit breaker flag) @return A boolean data type returning the new value of emergencyStopSwitch (circuit breaker flag) | function emergencyStopFunction (bool emergencySwitchValue)
public
verifyOwnerESC
returns(bool _emergencyStopSwitch)
{
emit LogEmergencyStopSwitch(emergencySwitchValue);
emergencyStopSwitch = emergencySwitchValue;
return emergencyStopSwitch;
}
| 13,017,132 | [
1,
351,
24530,
4947,
2083,
1435,
432,
445,
716,
5360,
3637,
801,
24530,
4947,
10200,
261,
24987,
898,
264,
2982,
13,
358,
638,
578,
629,
225,
801,
24530,
10200,
620,
432,
1250,
501,
618,
364,
12770,
326,
919,
434,
801,
24530,
4947,
10200,
261,
24987,
898,
264,
2982,
13,
327,
432,
1250,
501,
618,
5785,
326,
394,
460,
434,
801,
24530,
4947,
10200,
261,
24987,
898,
264,
2982,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
801,
24530,
4947,
2083,
261,
6430,
801,
24530,
10200,
620,
13,
203,
565,
1071,
203,
565,
3929,
5541,
41,
2312,
203,
565,
1135,
12,
6430,
389,
351,
24530,
4947,
10200,
13,
203,
565,
288,
203,
3639,
3626,
1827,
1514,
24530,
4947,
10200,
12,
351,
24530,
10200,
620,
1769,
203,
3639,
801,
24530,
4947,
10200,
273,
801,
24530,
10200,
620,
31,
203,
3639,
327,
801,
24530,
4947,
10200,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
// Copyright 2019 OpenST Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
//
// http://www.simpletoken.org/
//
// ----------------------------------------------------------------------------
import "./EIP20Interface.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
* @title EIP20Token contract.
*
* @notice EIP20Token implements EIP20Interface.
*/
contract EIP20Token is EIP20Interface {
/* Usings */
using SafeMath for uint256;
/** Name of the token. */
string private tokenName;
/** Symbol of the token. */
string private tokenSymbol;
/** Decimals used by the token. */
uint8 private tokenDecimals;
/** Total supply of the token. */
uint256 internal totalTokenSupply;
/** Stores the token balance of the accounts. */
mapping(address => uint256) balances;
/** Stores the authorization information. */
mapping(address => mapping (address => uint256)) allowed;
/* Constructor */
/**
* @notice Contract constructor.
*
* @param _symbol Symbol of the token.
* @param _name Name of the token.
* @param _decimals Decimal places of the token.
*/
constructor(
string memory _symbol,
string memory _name,
uint8 _decimals
)
public
{
tokenSymbol = _symbol;
tokenName = _name;
tokenDecimals = _decimals;
totalTokenSupply = 0;
}
/* Public functions. */
/**
* @notice Public function to get the name of the token.
*
* @return tokenName_ Name of the token.
*/
function name() public view returns (string memory tokenName_) {
tokenName_ = tokenName;
}
/**
* @notice Public function to get the symbol of the token.
*
* @return tokenSymbol_ Symbol of the token.
*/
function symbol() public view returns (string memory tokenSymbol_) {
tokenSymbol_ = tokenSymbol;
}
/**
* @notice Public function to get the decimals of the token.
*
* @return tokenDecimals Decimals of the token.
*/
function decimals() public view returns (uint8 tokenDecimals_) {
tokenDecimals_ = tokenDecimals;
}
/**
* @notice Get the balance of an account.
*
* @param _owner Address of the owner account.
*
* @return balance_ Account balance of the owner account.
*/
function balanceOf(address _owner) public view returns (uint256 balance_) {
balance_ = balances[_owner];
}
/**
* @notice Public function to get the total supply of the tokens.
*
* @dev Get totalTokenSupply as view so that child cannot edit.
*
* @return totalTokenSupply_ Total token supply.
*/
function totalSupply()
public
view
returns (uint256 totalTokenSupply_)
{
totalTokenSupply_ = totalTokenSupply;
}
/**
* @notice Public function to get the allowance.
*
* @param _owner Address of the owner account.
* @param _spender Address of the spender account.
*
* @return allowance_ Remaining allowance for the spender to spend from
* owner's account.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256 allowance_)
{
allowance_ = allowed[_owner][_spender];
}
/**
* @notice Public function to transfer the token.
*
* @dev Fires the transfer event, throws if, _from account does not have
* enough tokens to spend.
*
* @param _to Address to which tokens are transferred.
* @param _value Amount of tokens to be transferred.
*
* @return success_ `true` for a successful transfer, `false` otherwise.
*/
function transfer(
address _to,
uint256 _value
)
public
returns (bool success_)
{
success_ = transferBalance(msg.sender, _to, _value);
}
/**
* @notice Public function transferFrom.
*
* @dev Allows a contract to transfer tokens on behalf of _from address
* to _to address, the function caller has to be pre-authorized for
* multiple transfers up to the total of _value amount by the _from
* address.
*
* @param _from Address from which tokens are transferred.
* @param _to Address to which tokens are transferred.
* @param _value Amount of tokens transferred.
*
* @return success_ `true` for a successful transfer, `false` otherwise.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool success_)
{
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
success_ = transferBalance(_from, _to, _value);
}
/**
* @notice Public function to approve an account for transfer.
*
* @dev Allows _spender address to withdraw from function caller's account,
* multiple times up to the _value amount, if this function is called
* again it overwrites the current allowance with _value.
*
* @param _spender Address authorized to spend from the function caller's
* address.
* @param _value Amount up to which spender is authorized to spend.
*
* @return bool `true` for a successful approval, `false` otherwise.
*/
function approve(
address _spender,
uint256 _value
)
public
returns (bool success_)
{
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
success_ = true;
}
/* Internal functions. */
/**
* @notice Internal function to transfer the tokens.
*
* @dev This is an internal functions that transfers the token. This
* function is called from transfer and transferFrom functions.
*
* @param _from Address from which tokens are transferred.
* @param _to Address to which tokens are transferred.
* @param _value Amount of tokens transferred.
*
* @return success_ `true` for a successful transfer, `false` otherwise.
*/
function transferBalance(
address _from,
address _to,
uint256 _value
)
internal
returns (bool success_)
{
/**
* According to the EIP20 spec, "transfers of 0 values MUST be treated
* as normal transfers and fire the Transfer event".
* Also, should throw if not enough balance. This is taken care of by
* SafeMath.
*/
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
success_ = true;
}
}
| * @notice Public function to transfer the token. @dev Fires the transfer event, throws if, _from account does not have enough tokens to spend. @param _to Address to which tokens are transferred. @param _value Amount of tokens to be transferred. @return success_ `true` for a successful transfer, `false` otherwise./ | function transfer(
address _to,
uint256 _value
)
public
returns (bool success_)
{
success_ = transferBalance(msg.sender, _to, _value);
}
| 12,879,439 | [
1,
4782,
445,
358,
7412,
326,
1147,
18,
225,
478,
2814,
326,
7412,
871,
16,
1216,
309,
16,
389,
2080,
2236,
1552,
486,
1240,
1377,
7304,
2430,
358,
17571,
18,
225,
389,
869,
5267,
358,
1492,
2430,
854,
906,
4193,
18,
225,
389,
1132,
16811,
434,
2430,
358,
506,
906,
4193,
18,
327,
2216,
67,
1375,
3767,
68,
364,
279,
6873,
7412,
16,
1375,
5743,
68,
3541,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
12,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
1132,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1135,
261,
6430,
2216,
67,
13,
203,
565,
288,
203,
3639,
2216,
67,
273,
7412,
13937,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping(address => uint256) private authorizedContracts;
uint8 private constant PAYOUT_PERCENTAGE = 150;
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
struct Airline {
bool isRegistered;
bool isFunded;
uint256 funds;
}
mapping(address => Airline) private registeredAirlines; // track registered airlines, for multi-sig and airline ante
uint256 public totalRegisteredAirlines = 0;
// Insurance from passengers
struct Insurance {
address passenger;
uint256 insuranceCost;
uint256 payoutPercentage;
bool isPayoutCredited;
}
// mapping(bytes32 => Insurance[]) public flightKeyInsurance;
mapping(bytes32 => Insurance) public passengerInsurance; // (encoded passenger+flightKey => Insurance)
mapping(address => uint256) public passengerCredits; // passenger => insurance payouts in eth, pending withdrawal
struct Flight {
address airline;
uint8 statusCode;
uint256 timestamp;
string flightNo;
string departureFrom;
string arrivalAt;
bool isRegistered;
address[] insurees;
}
mapping(bytes32 => Flight) public flights; // key => Flight
uint256 public totalRegisteredFlights = 0;
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(address airlineAddress) public {
contractOwner = msg.sender;
registeredAirlines[airlineAddress] = Airline(true, false, 0); // initialise and register first airline
++totalRegisteredAirlines;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the function caller to be an authorized account
*/
modifier requireIsCallerAuthorized() {
require(
authorizedContracts[msg.sender] == 1,
"Caller is not authorized"
);
_;
}
/**
* @dev Modifier that requires the airline to be registered (may not be funded yet)
*/
modifier requireAirlineIsRegistered(address airlineAddress) {
require(
registeredAirlines[airlineAddress].isRegistered == true,
"Caller is not a registered airline"
);
_;
}
/**
* @dev Modifier that requires the ariline to be funded
*/
modifier requireAirlineIsFunded(address airlineAddress) {
require(
registeredAirlines[airlineAddress].isFunded == true,
"Caller's account is not funded yet"
);
_;
}
/**
* @dev Modifier that requires the flight to be registered
*/
modifier requireRegisteredFlight(bytes32 key) {
require(
flights[key].isRegistered == true,
"Flight is not registered yet"
);
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns (bool) {
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode) public requireContractOwner {
operational = mode;
}
/**
* @dev Authorize a contract address (FlightSuretyApp contract)
*/
function authorizeContract(address contractAddress)
public
requireContractOwner
{
authorizedContracts[contractAddress] = 1;
}
/**
* @dev Deauthorize a contract address (FlightSuretyApp contract)
*/
function deauthorizeContract(address contractAddress)
public
requireContractOwner
{
delete authorizedContracts[contractAddress];
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/* AIRLINE FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
* Only funded airlines can be
*/
function registerAirline(address newAirlineAddress)
external
requireIsOperational
requireIsCallerAuthorized
{
// Check that airline is not already registered
require(
!registeredAirlines[newAirlineAddress].isRegistered,
"Airline is already registered"
);
registeredAirlines[newAirlineAddress] = Airline({
isRegistered: true,
isFunded: false,
funds: 0
});
++totalRegisteredAirlines;
}
/**
* @dev Check an airline's registration status
*
*/
function isRegisteredAirline(address airlineAddress)
external
view
requireIsOperational
returns (bool)
{
return registeredAirlines[airlineAddress].isRegistered;
}
/**
* @dev Check an airline's funding status
*
*/
function isFundedAirline(address airlineAddress)
external
view
requireIsOperational
returns (bool)
{
return registeredAirlines[airlineAddress].isFunded;
}
/**
* @dev Check an airline's funding amount
*
*/
function getFundsForAirline(address airlineAddress)
external
view
requireIsOperational
returns (uint256)
{
return registeredAirlines[airlineAddress].funds;
}
/**
* @dev Get total number of registered airlines
*
*/
function getTotalRegisteredAirlines()
external
view
requireIsOperational
returns (uint256)
{
return totalRegisteredAirlines;
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund(address airlineAddress, uint256 amount)
external
payable
requireIsOperational
returns (bool)
{
require(
registeredAirlines[airlineAddress].isRegistered,
"Airline is not registered yet"
);
registeredAirlines[airlineAddress].isFunded = true;
registeredAirlines[airlineAddress].funds += amount;
return registeredAirlines[airlineAddress].isFunded;
}
/* PASSENGER FUNCTIONS */
/********************************************************************************************/
/**
* @dev Buy insurance for a flight
*
*/
function buy(
address passenger,
address airline,
string flightNo,
uint256 timestamp,
uint256 cost
) external payable requireIsOperational {
bytes32 key = getFlightKey(airline, flightNo, timestamp);
bytes32 insuranceKey = keccak256(abi.encodePacked(passenger, key));
passengerInsurance[insuranceKey] = Insurance({
passenger: passenger,
insuranceCost: cost,
payoutPercentage: PAYOUT_PERCENTAGE,
isPayoutCredited: false
});
flights[key].insurees.push(passenger);
}
function isPassengerInsured(
address passenger,
address airline,
string flightNo,
uint256 timestamp
) external view requireIsOperational returns (bool) {
bytes32 key = getFlightKey(airline, flightNo, timestamp);
bytes32 insuranceKey = keccak256(abi.encodePacked(passenger, key));
return passengerInsurance[insuranceKey].passenger == passenger;
}
/**
* @dev Credits payouts to insuree
*/
function creditInsuree(address passenger, bytes32 key)
internal
requireIsOperational
{
bytes32 insuranceKey = keccak256(abi.encodePacked(passenger, key));
require(
passengerInsurance[insuranceKey].passenger == passenger,
"Passenger does not own insurance for this flight"
);
require(
!passengerInsurance[insuranceKey].isPayoutCredited,
"Passenger has already been credited"
);
// calculate payout
uint256 amount = passengerInsurance[insuranceKey]
.insuranceCost
.mul(passengerInsurance[insuranceKey].payoutPercentage)
.div(100);
passengerInsurance[insuranceKey].isPayoutCredited = true;
passengerCredits[passenger] += amount;
}
function getPassengerCredits(address passenger)
external
view
returns (uint256)
{
return passengerCredits[passenger];
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(address passenger) external payable requireIsOperational {
require(
passengerCredits[passenger] > 0,
"Passenger does not have credits to withdraw"
);
uint256 credits = passengerCredits[passenger];
passengerCredits[passenger] = 0;
passenger.transfer(credits);
}
/* FLIGHT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Register a new flight
*
*/
function registerFlight(
address airline,
string flightNo,
string departureFrom,
string arrivalAt,
uint256 timestamp
)
external
requireIsOperational
requireAirlineIsRegistered(airline)
requireAirlineIsFunded(airline)
returns (bytes32, bool)
{
require(
!flights[key].isRegistered,
"Flight has already been registered"
);
bytes32 key = getFlightKey(airline, flightNo, timestamp);
// Flight memory newFlight
flights[key] = Flight({
airline: airline,
statusCode: STATUS_CODE_UNKNOWN,
timestamp: timestamp,
flightNo: flightNo,
departureFrom: departureFrom,
arrivalAt: arrivalAt,
isRegistered: true,
insurees: new address[](0)
});
++totalRegisteredFlights;
return (key, flights[key].isRegistered);
}
function isRegisteredFlight(
address airline,
string flightNo,
uint256 timestamp
) external view requireIsOperational returns (bool) {
bytes32 key = getFlightKey(airline, flightNo, timestamp);
return flights[key].isRegistered;
}
function getFlightKey(
address airline,
string memory flight,
uint256 timestamp
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Save flight status info
*
*/
function processFlightStatus(
address airline,
string flightNo,
uint256 timestamp,
uint8 statusCode
) external requireIsOperational {
bytes32 key = getFlightKey(airline, flightNo, timestamp);
if (flights[key].statusCode == STATUS_CODE_UNKNOWN) {
flights[key].statusCode = statusCode;
if (statusCode == STATUS_CODE_LATE_AIRLINE) {
// airline is late, credit insured amount to passengers
uint256 numInsurees = flights[key].insurees.length;
for (uint256 i = 0; i < numInsurees; i++) {
creditInsuree(flights[key].insurees[i], key);
}
}
}
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function() external payable {}
}
| * @dev Modifier that requires the ariline to be funded/ | modifier requireAirlineIsFunded(address airlineAddress) {
require(
registeredAirlines[airlineAddress].isFunded == true,
"Caller's account is not funded yet"
);
_;
}
| 7,241,051 | [
1,
9829,
716,
4991,
326,
419,
12554,
358,
506,
9831,
785,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
2583,
29752,
1369,
2520,
42,
12254,
12,
2867,
23350,
1369,
1887,
13,
288,
203,
3639,
2583,
12,
203,
5411,
4104,
29752,
3548,
63,
1826,
1369,
1887,
8009,
291,
42,
12254,
422,
638,
16,
203,
5411,
315,
11095,
1807,
2236,
353,
486,
9831,
785,
4671,
6,
203,
3639,
11272,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// Creator: base64.tech
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./ERC721A.sol";
/*
_______ ___ _______ _______ _______ _______ ______ _______
| _ || | | || || || || _ | | |
| |_| || | | _ || _ || _ || ___|| | || | _____|
| || | | | | || | | || |_| || |___ | |_||_ | |_____
| _ | | |___ | |_| || |_| || ___|| ___|| __ ||_____ |
| |_| || || || || | | |___ | | | | _____| |
|_______||_______||_______||_______||___| |_______||___| |_||_______|
A METACITZN COLLECTION
developed by base64.tech
*/
contract Bloopers is ERC721A, Ownable {
using ECDSA for bytes32;
uint256 public constant TOTAL_MAX_SUPPLY = 10500 + 1; // MAX SUPPLY = 10500, +1 for gas optimization for use in conditional statements
uint256 public constant MAX_ALLOWLIST_MINT_PER_WALLET = 3 + 1; // MAX PUBLIC MINT PER WALLET = 3, +1 for gas optimization for use in conditional statements
uint256 public constant MAX_PUBLIC_MINT_PER_WALLET = 3 + 1; // MAX PUBLIC MINT PER WALLET = 3, +1 for gas optimization for use in conditional statements
uint256 public constant TOKEN_PRICE = .088 ether;
address public signatureVerifier;
bool public publicSaleActive;
bool public preSaleActive;
bool public freeClaimActive;
mapping(bytes32 => bool) public usedHashes;
mapping(address => uint256) public numberFreeMinted;
mapping(address => uint256) public numberAllowListMinted;
mapping(address => uint256) public numberPublicMinted;
string private _baseTokenURI;
constructor() ERC721A("Bloopers", "BLOOPERS") {}
modifier callerIsUser() {
require(tx.origin == msg.sender, "The caller is another contract");
_;
}
modifier validateFreeClaimActive() {
require(freeClaimActive, "free claim is not active");
_;
}
modifier validatePreSaleActive() {
require(preSaleActive, "pre-sale is not active");
_;
}
modifier validatePublicSaleActive() {
require(publicSaleActive, "public sale is not active");
_;
}
modifier correctAmountSent(uint256 _quantity) {
require(msg.value >= TOKEN_PRICE * _quantity, "Need to send more ETH.");
_;
}
modifier underMaxSupply(uint256 _quantity) {
require(
_totalMinted() + _quantity < TOTAL_MAX_SUPPLY,
"Purchase would exceed max supply"
);
_;
}
function hashMessage(
address sender,
uint256 nonce,
uint256 maxAllocation
) public pure returns (bytes32) {
bytes32 hash = keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(sender, nonce, maxAllocation))
)
);
return hash;
}
function freeMint(
bytes memory _signature,
uint256 _quantity,
uint256 _nonce,
uint256 _maxAllocation
) external callerIsUser validateFreeClaimActive {
uint256 quantity = numberFreeMinted[msg.sender] + _quantity;
require(
quantity < _maxAllocation + 1,
"Mint would exceed maximum allocation for Free Mints for this wallet"
);
_bloopersMint(_signature, _quantity, _nonce, _maxAllocation);
numberFreeMinted[msg.sender] += _quantity;
}
function allowListMint(
bytes memory _signature,
uint256 _quantity,
uint256 _nonce
)
external
payable
callerIsUser
validatePreSaleActive
correctAmountSent(_quantity)
{
uint256 quantity = numberAllowListMinted[msg.sender] + _quantity;
require(
quantity < MAX_ALLOWLIST_MINT_PER_WALLET,
"Mint would exceed maximum allowList allocation for this wallet"
);
_bloopersMint(_signature, _quantity, _nonce, 3);
numberAllowListMinted[msg.sender] += _quantity;
}
function publicMint(
bytes memory _signature,
uint256 _quantity,
uint256 _nonce
)
external
payable
callerIsUser
validatePublicSaleActive
correctAmountSent(_quantity)
{
uint256 quantity = numberPublicMinted[msg.sender] + _quantity;
require(
quantity < MAX_PUBLIC_MINT_PER_WALLET,
"Mint would exceed maximum allocation for Public Mints for this wallet"
);
_bloopersMint(_signature, _quantity, _nonce, 3);
numberPublicMinted[msg.sender] += _quantity;
}
function _bloopersMint(
bytes memory _signature,
uint256 _quantity,
uint256 _nonce,
uint256 _maxAllocation
) private underMaxSupply(_quantity) {
bytes32 messageHash = hashMessage(msg.sender, _nonce, _maxAllocation);
require(
messageHash.recover(_signature) == signatureVerifier,
"Unrecognizable Hash"
);
require(usedHashes[messageHash] == false, "Hash was already used");
usedHashes[messageHash] = true;
_mint(msg.sender, _quantity, "", false);
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function numberMinted(address owner) public view returns (uint256) {
return _numberMinted(owner);
}
function getOwnershipData(uint256 tokenId)
external
view
returns (TokenOwnership memory)
{
return _ownershipOf(tokenId);
}
/* OWNER FUNCTIONS */
function ownerMint(uint256 _numberToMint)
external
onlyOwner
underMaxSupply(_numberToMint)
{
_mint(msg.sender, _numberToMint, "", false);
}
function ownerMintToAddress(address _recipient, uint256 _numberToMint)
external
onlyOwner
underMaxSupply(_numberToMint)
{
_mint(_recipient, _numberToMint, "", false);
}
function setBaseURI(string calldata baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function withdrawFunds() external onlyOwner {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer failed.");
}
function setSignatureVerifier(address _signatureVerifier)
external
onlyOwner
{
signatureVerifier = _signatureVerifier;
}
function flipPublicSaleActive() external onlyOwner {
publicSaleActive = !publicSaleActive;
}
function flipPreSaleActive() external onlyOwner {
preSaleActive = !preSaleActive;
}
function flipFreeClaimActive() external onlyOwner {
freeClaimActive = !freeClaimActive;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/Context.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerQueryForNonexistentToken();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is equivalent to _burn(tokenId, false)
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.startTimestamp = uint64(block.timestamp);
currSlot.burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | MAX PUBLIC MINT PER WALLET = 3, +1 for gas optimization for use in conditional statements
| uint256 public constant MAX_ALLOWLIST_MINT_PER_WALLET = 3 + 1; | 14,423,829 | [
1,
6694,
17187,
490,
3217,
10950,
30293,
15146,
273,
890,
16,
397,
21,
364,
16189,
14850,
364,
999,
316,
11139,
6317,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
5381,
4552,
67,
13511,
7085,
67,
49,
3217,
67,
3194,
67,
59,
1013,
15146,
273,
890,
397,
404,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0xb72CC84D4538278fc7647915c62b6E772583158e/sources/contracts/ERC721.sol | TemplateId, x, y, z
| string[] memory paramParts = String.split(paramsString, ","); | 14,210,370 | [
1,
2283,
548,
16,
619,
16,
677,
16,
998,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
533,
8526,
3778,
579,
4305,
273,
514,
18,
4939,
12,
2010,
780,
16,
5753,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.0;
/// @author Jaime Caso
/// @title A Electronic Medical Record System
contract MedicalRecord {
address private owner;
struct Record {
address doctor;
address patient;
string hash;
string encoding;
bool verified;
}
// Roles
mapping(address => Doctor) public doctorProfile;
mapping(address => Patient) public patientProfile;
// Records
mapping(string => Record) public recordData;
// Events
event createDoctorLog(address _doctor);
event requestDoctorLog(address _doctor, address _patient);
event patientAddedByDoctorLog(address _doctor, address _patient);
event verifiedRecordLog(address _patient, string _hash);
// Set the owner ot this contract just once
// Consider use Initializer to make the contract upgradable
constructor() {
owner = msg.sender;
}
/** Register as Patient. */
function registerAsPatient(string memory _name) public returns (bool) {
Patient p = new Patient(_name);
patientProfile[msg.sender] = p;
return true;
}
/** Add a new Doctor. */
function addDoctor(address _doctor, string memory _name, string memory _url, string memory _metadataHash) public isOwner() returns (bool) {
doctorProfile[_doctor] = new Doctor(_name, _url, _metadataHash);
// Event
emit createDoctorLog(_doctor);
return true;
}
/** Request a doctor. */
function requestDoctor(address _doctor) public returns (bool) {
require(doctorProfile[_doctor].getOpen(), "The doctor is closed to new patients");
patientProfile[msg.sender].requestDoctor(_doctor);
// Event
emit requestDoctorLog(_doctor, msg.sender);
return true;
}
function doctorInPatient(address _doctor, address _patient) view public returns (bool){
require(patientProfile[_patient].isActive(), "The patient must be activated");
return patientProfile[_patient].containsDoctor(_doctor);
}
/** Add a new Patient to the doctor mapping. */
function addNewPatient(address _patient) public isDoctor() doctorIsAllowed(_patient) returns (bool) {
doctorProfile[msg.sender].addPatient(_patient);
// Event
emit patientAddedByDoctorLog(msg.sender, _patient);
return true;
}
function patientInDoctor(address _patient, address _doctor) view public returns (bool){
require(doctorProfile[_doctor].isActive(), "The doctor must be activated");
return doctorProfile[_doctor].isPatient(_patient);
}
/** Add as a new record. */
function addRecord(address _patient, string memory _hash, string memory _encoding) public isDoctor() doctorIsAllowed(_patient) returns (bool) {
Record memory r = Record(msg.sender, _patient, _hash, _encoding, false);
recordData[_hash] = r;
// Event
return true;
}
/** verify a record. */
function verifyRecord(string memory _hash) public returns (bool) {
require(recordData[_hash].patient == msg.sender, "Just the patient can verify the record");
recordData[_hash].verified = true;
// Event
emit verifiedRecordLog(msg.sender, _hash);
return true;
}
/** get a specific record. */
function getRecord(string memory _hash) view public returns (address, address, string memory, bool) {
require(recordData[_hash].doctor != address(0), "The record does not exist");
return (recordData[_hash].doctor,
recordData[_hash].patient,
recordData[_hash].encoding,
recordData[_hash].verified);
}
function getPatient(address _patient) view public returns (string memory, bool) {
require(patientProfile[_patient].active(), "The patient does not exist or is deactivated");
return patientProfile[_patient].getAttrs();
}
function getDoctor(address _doctor) view public returns (string memory, string memory, string memory, bool, bool) {
require(doctorProfile[_doctor].active(), "The doctor does not exist or is deactivated");
return doctorProfile[_doctor].getAttrs();
}
function switchActiveDoctor() isDoctor() public {
bool open = !doctorProfile[msg.sender].getOpen();
doctorProfile[msg.sender].setOpen(open);
}
function addrIsPatient(address _patient) view public returns (bool) {
return patientProfile[_patient].isActive();
}
function addrIsDoctor(address _doctor) view public returns (bool) {
return doctorProfile[_doctor].isActive();
}
/** Valid username requirement. */
modifier isOwner() {
require(owner == msg.sender, "The caller is not the admin");
_;
}
/** Valid username requirement. */
modifier isDoctor() {
require(addrIsDoctor(msg.sender), "The doctor is no activated");
_;
}
/** Valid username requirement. */
modifier doctorIsAllowed(address _patient) {
require(patientProfile[_patient].containsDoctor(msg.sender), "The doctor is not allowed");
_;
}
}
contract Patient {
string public name;
bool public active;
mapping(address => bool) public doctorAccess;
constructor(string memory _name) {
name = _name;
active = true;
}
function requestDoctor(address _doctor) public {
doctorAccess[_doctor] = true;
}
function revokeDoctor(address _doctor) public {
doctorAccess[_doctor] = false;
}
function containsDoctor(address _doctor) view public returns (bool){
return doctorAccess[_doctor];
}
function isActive() view public returns (bool){
return active;
}
function getAttrs() view public returns (string memory, bool){
return (name, active);
}
}
contract Doctor {
string public name;
string public url;
string public metadataHash;
bool public open;
bool public active;
mapping(address => bool) public patients;
constructor(string memory _name, string memory _url, string memory _metadataHash) {
name = _name;
url = _url;
metadataHash = _metadataHash;
open = false;
active = true;
}
function getOpen() public view returns (bool){
return open;
}
function setOpen(bool _open) public {
open = _open;
}
function isActive() view public returns (bool){
return active;
}
function addPatient(address _patient) public {
patients[_patient] = true;
}
function isPatient(address _patient) view public returns (bool){
return patients[_patient];
}
function deletePatient(address _patient) public {
patients[_patient] = false;
}
function getAttrs() view public returns (string memory, string memory, string memory, bool, bool){
return (name, url, metadataHash, open, active);
}
}
| * verify a record. */ Event | function verifyRecord(string memory _hash) public returns (bool) {
require(recordData[_hash].patient == msg.sender, "Just the patient can verify the record");
recordData[_hash].verified = true;
emit verifiedRecordLog(msg.sender, _hash);
return true;
}
| 13,057,255 | [
1,
8705,
279,
1409,
18,
342,
2587,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3929,
2115,
12,
1080,
3778,
389,
2816,
13,
1071,
1135,
261,
6430,
13,
288,
203,
203,
3639,
2583,
12,
3366,
751,
63,
67,
2816,
8009,
16330,
1979,
422,
1234,
18,
15330,
16,
315,
19642,
326,
18608,
848,
3929,
326,
1409,
8863,
203,
3639,
23065,
63,
67,
2816,
8009,
19685,
273,
638,
31,
203,
203,
3639,
3626,
13808,
2115,
1343,
12,
3576,
18,
15330,
16,
389,
2816,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @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 {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
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 {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// 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
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/**
* @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
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
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 returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @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
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit 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;
emit MintFinished();
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
pragma solidity^0.4.18;
contract AlphaconToken is CanReclaimToken, MintableToken, BurnableToken, PausableToken {
string public name = "Alphacon Token";
string public symbol = "ALP";
uint8 public decimals = 18;
}
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <remco@2π.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this ether.
* @notice Ether can still be sent to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
owner.transfer(address(this).balance);
}
}
pragma solidity^0.4.24;
/**
* @title AlphaconCustomToken
* @notice AlphaconCustomToken permits one more token generation after
* token sale finalized. The generated token _amount is limited
* up to 10% of total supply before the generation.
*/
contract AlphaconCustomToken is HasNoEther, CanReclaimToken, AlphaconToken {
/* State */
bool public tokenGenerated;
uint256 public constant TARGET_TOTAL_SUPPLY = 25e27; // 25 Billion ALP
/* Event */
event MintAfterSale(address _to, uint _preSupply, uint _postSupply);
/* External */
/**
* @notice After crowdsale finalized, mint additional tokens for ESC-LOCK.
* This generation only happens once.
*/
function mintAfterSale() external onlyOwner returns (bool) {
require(!tokenGenerated);
// valid only after finishMinting is executed
require(mintingFinished);
// revert if total supply is more than TARGET_TOTAL_SUPPLY
uint256 preSupply = totalSupply();
require(preSupply < TARGET_TOTAL_SUPPLY);
uint256 amount = TARGET_TOTAL_SUPPLY.sub(preSupply);
// mint token internally
totalSupply_ = TARGET_TOTAL_SUPPLY;
balances[owner] = balances[owner].add(amount);
emit Transfer(address(0), owner, amount);
tokenGenerated = true;
emit MintAfterSale(owner, preSupply, totalSupply());
return true;
}
} | * @title AlphaconCustomToken @notice AlphaconCustomToken permits one more token generation after token sale finalized. The generated token _amount is limited up to 10% of total supply before the generation./ | contract AlphaconCustomToken is HasNoEther, CanReclaimToken, AlphaconToken {
bool public tokenGenerated;
event MintAfterSale(address _to, uint _preSupply, uint _postSupply);
function mintAfterSale() external onlyOwner returns (bool) {
require(!tokenGenerated);
require(mintingFinished);
uint256 preSupply = totalSupply();
require(preSupply < TARGET_TOTAL_SUPPLY);
uint256 amount = TARGET_TOTAL_SUPPLY.sub(preSupply);
totalSupply_ = TARGET_TOTAL_SUPPLY;
balances[owner] = balances[owner].add(amount);
emit Transfer(address(0), owner, amount);
tokenGenerated = true;
emit MintAfterSale(owner, preSupply, totalSupply());
return true;
}
} | 10,764,399 | [
1,
9690,
591,
3802,
1345,
225,
24277,
591,
3802,
1345,
4641,
1282,
1245,
1898,
1147,
9377,
1839,
540,
1147,
272,
5349,
727,
1235,
18,
1021,
4374,
1147,
389,
8949,
353,
13594,
540,
731,
358,
1728,
9,
434,
2078,
14467,
1865,
326,
9377,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
24277,
591,
3802,
1345,
353,
4393,
2279,
41,
1136,
16,
4480,
426,
14784,
1345,
16,
24277,
591,
1345,
288,
203,
225,
1426,
1071,
1147,
7823,
31,
203,
203,
225,
871,
490,
474,
4436,
30746,
12,
2867,
389,
869,
16,
2254,
389,
1484,
3088,
1283,
16,
2254,
389,
2767,
3088,
1283,
1769,
203,
203,
225,
445,
312,
474,
4436,
30746,
1435,
3903,
1338,
5541,
1135,
261,
6430,
13,
288,
203,
565,
2583,
12,
5,
2316,
7823,
1769,
203,
203,
565,
2583,
12,
81,
474,
310,
10577,
1769,
203,
203,
565,
2254,
5034,
675,
3088,
1283,
273,
2078,
3088,
1283,
5621,
203,
565,
2583,
12,
1484,
3088,
1283,
411,
16964,
67,
28624,
67,
13272,
23893,
1769,
203,
565,
2254,
5034,
3844,
273,
16964,
67,
28624,
67,
13272,
23893,
18,
1717,
12,
1484,
3088,
1283,
1769,
203,
203,
565,
2078,
3088,
1283,
67,
273,
16964,
67,
28624,
67,
13272,
23893,
31,
203,
565,
324,
26488,
63,
8443,
65,
273,
324,
26488,
63,
8443,
8009,
1289,
12,
8949,
1769,
203,
565,
3626,
12279,
12,
2867,
12,
20,
3631,
3410,
16,
3844,
1769,
203,
203,
565,
1147,
7823,
273,
638,
31,
203,
203,
565,
3626,
490,
474,
4436,
30746,
12,
8443,
16,
675,
3088,
1283,
16,
2078,
3088,
1283,
10663,
203,
203,
565,
327,
638,
31,
203,
225,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.9;
import "./BDERC1155Tradable.sol";
import "./IWarrior.sol";
import "./IRegion.sol";
//Import ERC1155 standard for utilizing FAME tokens
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
///@title LootChestCollectible
///@notice The contract for managing BattleDrome Loot Chest Tokens
contract LootChestCollectible is BDERC1155Tradable, ERC1155Holder {
//////////////////////////////////////////////////////////////////////////////////////////
// Config
//////////////////////////////////////////////////////////////////////////////////////////
//Fungible Token Tiers
enum ChestType {
NULL,
BRONZE,
SILVER,
GOLD,
DIAMOND
}
//Chest level multipliers are used in math throughout, this is done by taking the integerized value of ChestType
//ie:
// bronze = 1
// silver = 2
// gold = 3
// diamond = 4
//And then taking 2 ^ ({val}-1)
//So the resulting multipliers would be for example:
// bronze = 1
// silver = 2
// gold = 4
// diamond = 8
//Chest Contents Constants
//Base value is multiplied by the appropriate chest level multiplier
uint constant FIXED_VALUE_BASE = 125;
//Chance Constants - chance/10000 eg: 100.00%
//This applies to the bronze level chests, each subsequent chest has chances multiplied by it's multiplier
uint constant CHANCE_BONUS_10 = 500; //5% - Bronze, 10% - Silver, 20% - Gold, 40% - Diamond
uint constant CHANCE_BONUS_25 = 200; //2% - Bronze, 4% - Silver, 8% - Gold, 16% - Diamond
uint constant CHANCE_BONUS_50 = 100; //1% - Bronze, 2% - Silver, 4% - Gold, 8% - Diamond
uint constant CHANCE_BONUS_WARRIOR = 100; //1% - Bronze, 2% - Silver, 4% - Gold, 8% - Diamond
uint constant CHANCE_BONUS_REGION = 5; //0.05% - Bronze, 0.1% - Silver, 0.2% - Gold, 0.4% - Diamond
//Costing Constants
uint constant ICO_BASE_FAME_VALUE = 10000000 gwei;
uint constant NEW_FAME_PER_OLD = 1000;
uint constant NEW_FAME_ICO_VALUE = ICO_BASE_FAME_VALUE / NEW_FAME_PER_OLD;
uint constant VOLUME_DISCOUNT_PERCENT = 1; //Cost break when increasing tier when calculating cost of a chest tier
//ie: this percentage is multiplied by the multiplier, and applied as a discount to price
uint constant MIN_DEMAND_RATIO = 5000; //Percent * 10000 similar to chances above
uint constant MAX_DEMAND_RATIO = 20000; //Percent * 10000 similar to chances above
//Other Misc Config Constants
uint8 constant RECENT_SALES_TO_TRACK = 64; //Max of last 32 sales
uint constant RECENT_SALES_TIME_SECONDS = 86400 * 30; //Max of last 30 days
//////////////////////////////////////////////////////////////////////////////////////////
// Structs
//////////////////////////////////////////////////////////////////////////////////////////
struct ChestSale {
uint64 timestamp;
uint8 chest_type;
uint32 quantity;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Local Storage Variables
//////////////////////////////////////////////////////////////////////////////////////////
//Associated Contracts
IERC1155 FAMEContract;
uint256 FAMETokenID;
IWarrior WarriorContract;
IRegion RegionContract;
//Sales History (Demand Tracking)
ChestSale[RECENT_SALES_TO_TRACK] recentSales;
uint currentSaleIndex = 0;
//////////////////////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////////////////////
constructor(address _proxyRegistryAddress)
BDERC1155Tradable(
"LootChestCollectible",
"BDLC",
_proxyRegistryAddress,
"https://metadata.battledrome.io/api/erc1155-loot-chest/"
)
{
}
//////////////////////////////////////////////////////////////////////////////////////////
// Errors
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice The contract does not have sufficient FAME to support `requested` chests of type `chestType`, maximum of `maxPossible` can be created with current balance.
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param requested The number of chests requested
*@param maxPossible The maximum number of chests of the requested type that can be created with current balance
*/
error InsufficientContractBalance(uint8 chestType, uint256 requested, uint256 maxPossible);
/**
*@notice Insufficient Ether sent for the requested action. You sent `sent` Wei but `required` Wei was required
*@param sent The amount of Ether (in Wei) that was sent by the caller
*@param required The amount of Ether (in Wei) that was actually required for the requested action
*/
error InsufficientEther(uint256 sent, uint256 required);
/**
*@notice Insufficient Chests of type: `chestType`, you only have `balance` chests of that type!
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param balance The number of chests the user currently has of the specified type
*/
error InsufficientChests(uint8 chestType, uint256 balance);
/**
*@notice Error minting new Warrior NFT!
*@param code Error Code
*/
error ErrorMintingWarrior(uint code);
/**
*@notice Error minting new Region NFT!
*@param code Error Code
*/
error ErrorMintingRegion(uint code);
//////////////////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice Indicates that a user `opener` opened `quantity` chests of type `chestType` at `timeStamp`
*@param opener The address that opened the chests
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param quantity The number of chests opened in this event
*@param timeStamp the timestamp that the chests were opened
*@param fame The amount of FAME found in the box(s)
*@param warriors The number of warriors found in the box(s)
*@param regions The number of regions found in the box(s)
*/
event LootBoxOpened(address indexed opener, uint8 indexed chestType, uint32 quantity, uint32 timeStamp, uint32 fame, uint32 warriors, uint32 regions);
//////////////////////////////////////////////////////////////////////////////////////////
// ERC1155 Overrides/Functions
//////////////////////////////////////////////////////////////////////////////////////////
function contractURI() public pure returns (string memory) {
return "https://metadata.battledrome.io/contract/erc1155-loot-chest";
}
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _amount,
bytes calldata _data
) public override returns (bytes4) {
require(
(
(msg.sender == address(FAMEContract) && _id == FAMETokenID) || //Allow reciept of FAME tokens
msg.sender == address(RegionContract) || //Allow Region Contract to send us Region NFTs (to forward to users)
msg.sender == address(this) //Allow any internal transaction originated here
),
"INVALID_TOKEN!" //Otherwise kick back INVALID_TOKEN error code, preventing the transfer.
);
bytes4 rv = super.onERC1155Received(_operator, _from, _id, _amount, _data);
return rv;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(BDERC1155Tradable, ERC1155Receiver)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Loot Box Buy/Sell
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice Buy a number of chests of the specified type, paying ETH
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param quantity The number of chests to buy
*/
function buy(ChestType chestType, uint quantity) public payable {
//First, is it possible to buy the proposed chests? If not, then revert to prevent people wasting money
uint maxCreatable = maxSafeCreatable(chestType);
if(maxCreatable >= quantity){
//We have sufficient balance to create at least the requested amount
//So calculate the required price of the requested chests:
uint price = getPrice(chestType) * quantity;
//Did the user send enough?
if(msg.value>=price){
//Good, they paid enough... Let's mint their chests then!
_mint(msg.sender, uint(chestType), quantity, "");
tokenSupply[uint(chestType)] = tokenSupply[uint(chestType)] + quantity; //Because we're bypassing the normal mint function.
ChestSale storage saleRecord = recentSales[(currentSaleIndex++)%RECENT_SALES_TO_TRACK];
saleRecord.timestamp = uint64(block.timestamp);
saleRecord.chest_type = uint8(chestType);
saleRecord.quantity = uint32(quantity);
//Check if they overpaid and refund:
if(msg.value>price){
payable(msg.sender).transfer(msg.value-price);
}
}else{
//Bad monkey! Not enough money!
revert InsufficientEther(msg.value,price);
}
}else{
//Insufficient balance, throw error:
revert InsufficientContractBalance(uint8(chestType), quantity, maxCreatable);
}
}
/**
*@notice Sell a number of FAME back to the contract, in exchange for whatever the current payout is.
*@param quantity The number of FAME to sell
*/
function sell(uint quantity) public {
uint payOutAmount = getBuyBackPrice(quantity);
transferFAME(msg.sender,address(this),quantity);
require(address(this).balance>=payOutAmount,"CONTRACT BALANCE ERROR!");
if(payOutAmount>0) payable(msg.sender).transfer(payOutAmount);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Loot Box Opening
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice Open a number of your owned chests of the specified type
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param quantity The number of chests to open
*@return fameReward The amount of FAME found in the chests
*@return warriors The number of bonus Warriors found in the chests
*@return regions The number of bonus Regions found in the chests
*/
function open(ChestType chestType, uint quantity) public ownersOnly(uint(chestType)) returns (uint fameReward, uint warriors, uint regions) {
//First let's confirm if the user actually owns enough chests of the appropriate type that they've requested
uint balance = balanceOf(msg.sender, uint(chestType));
if(balance >= quantity){
fameReward = 0;
warriors = 0;
regions = 0;
uint chestTypeMultiplier = (2**(uint(chestType)-1));
uint baseFAMEReward = FIXED_VALUE_BASE * chestTypeMultiplier;
//Burn the appropriate number of chests:
_burn(msg.sender,uint(chestType),quantity);
//Iterate the chests requested to calculate rewards
for(uint chest=0;chest<quantity;chest++){
//Calculate the FAME Reward amount for this chest:
uint fameRoll = roll(chest*2+0);
if(fameRoll<(CHANCE_BONUS_50 * chestTypeMultiplier)){
fameReward += baseFAMEReward * 1500 / 1000;
}else if(fameRoll<(CHANCE_BONUS_25 * chestTypeMultiplier)){
fameReward += baseFAMEReward * 1250 / 1000;
}else if(fameRoll<(CHANCE_BONUS_10 * chestTypeMultiplier)){
fameReward += baseFAMEReward * 1100 / 1000;
}else{
fameReward += baseFAMEReward;
}
//Calculate if any prize (NFT) was also received in this chest:
uint prizeRoll = roll(chest*2+1);
if(prizeRoll<(CHANCE_BONUS_REGION * chestTypeMultiplier)){
//Woohoo! Won a Region! BONUS!
regions++;
}else if(fameRoll<(CHANCE_BONUS_WARRIOR * chestTypeMultiplier)){
//Woohoo! Won a Warrior!
warriors++;
}
}
//Ok now that we've figured out their rewards, let's give it all to them!
//First the FAME:
transferFAME(address(this),msg.sender,fameReward);
//Now if there are regions or warriors in the rewards, mint the appropriate NFTs:
for(uint w=0;w<warriors;w++){
//Unfortunately because of how warrior minting works, we need to pre-generate some random traits:
// For the record this was chosen for a good reason, it's more flexible and supports a wider set of use cases
// But it is a bit more work when implementing in an external contract like this...
//First let's grab a random seed:
uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp,blockhash(block.number))));
//And then generate the remaining traits from it
uint16 colorHue = uint16(uint(keccak256(abi.encodePacked(randomSeed,uint8(1)))));
uint8 armorType = uint8(uint(keccak256(abi.encodePacked(randomSeed,uint8(2)))))%4;
uint8 shieldType = uint8(uint(keccak256(abi.encodePacked(randomSeed,uint8(3)))))%4;
uint8 weaponType = uint8(uint(keccak256(abi.encodePacked(randomSeed,uint8(4)))))%10;
//Now mint the warrior:
WarriorContract.mintCustomWarrior(msg.sender, 0, true, randomSeed, colorHue, armorType, shieldType, weaponType);
}
for(uint r=0;r<regions;r++){
//When minting Regions, the caller (this contract) will end up owning them, so we need to first mint, then change ownership:
//First we try to mint:
try RegionContract.trustedCreateRegion() returns (uint regionID){
//Now we transfer it to the user:
RegionContract.safeTransferFrom(address(this),msg.sender,regionID,1,"");
} catch Error(string memory reason) {
revert(reason);
} catch Panic(uint code) {
revert ErrorMintingRegion(code);
} catch (bytes memory) {
revert ErrorMintingRegion(0);
}
}
emit LootBoxOpened(msg.sender, uint8(chestType), uint32(quantity), uint32(block.timestamp), uint32(fameReward), uint32(warriors), uint32(regions));
}else{
//Bad monkey! You don't have that many chests to open!
revert InsufficientChests(uint8(chestType), balance);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Costing Getters
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice Get the Base Value (guaranteed FAME contents) of a given chest type
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@return value The Value (amount of FAME) included in the chest type
*/
function getBaseValue(ChestType chestType) public pure returns (uint value) {
require(chestType > ChestType.NULL && chestType <= ChestType.DIAMOND, "ILLEGAL CHEST TYPE");
value = FIXED_VALUE_BASE * (2**(uint(chestType)-1));
}
/**
*@notice Get the recent sales volume (total amount of FAME sold in chest Base Values)
*@return volume The total Base Value (guaranteed included FAME) of all recent chest sales
*@dev This is used to figure out demand for costing math
*/
function getRecentSalesVolume() public view returns (uint volume) {
volume = 1; //To avoid div/0
for(uint i = 0; i<RECENT_SALES_TO_TRACK; i++){
if(recentSales[i].timestamp >= block.timestamp - RECENT_SALES_TIME_SECONDS){
volume += getBaseValue(ChestType(recentSales[i].chest_type)) * recentSales[i].quantity;
}
}
}
/**
*@notice Calculate the current FAME price (price per FAME token in ETH)
*@return price The current ETH price (in wei) of a single FAME token
*@dev This is used to calculate the "market floor" price for FAME so that we can use it to caluclate cost of chests.
*/
function getCurrentFAMEPrice() public view returns (uint price) {
//First we look at the current (available/non-liable) fame balance, and the recent sales volume, and calculate a demand ratio:
// Note: recent sales volume is always floored at the value of at least one of the max chest, which allows
// for the situation where there is zero supply, to incentivize seeding the supply to accommodate chest sales.
// Otherwise, what happens is if the contract runs dry, and no sales happen because there is no supply, the
// "recent sales" drop to zero, resulting in artificially deflated demand, even though "demand" might be high, but
// it can't be observed because lack of supply has choked off sales. (not to mention it also helps avoid div/0)
//ie: if we have 10,000 FAME, and we've recently only sold 1000, then we have 10:1 ratio so plenty of supply to meet the demand
// however if we have 1000 FAME, and recently sold 2000, we have a 0.5:1 ratio, so low supply, which should drive up price...
//Price is calculated by first calculating demand ratio, and then clamping it to min/max range (in config constants)
//Then taking the ICO base value of new FAME, and dividing by the demand ratio.
//As a practical example, let's assume the ICO base value was 10,000gwei per fame,
//And assume we have a demand ratio clamp range of 0.5 - 2.0
//Then the following table demonstrates how the demand ratios would equate to FAME price
//0.5:1 - 20,000 gwei/FAME
//0.75:1 - 13,333 gwei/FAME
//1:1 - 10,000 gwei/FAME
//1.25:1 - 8,000 gwei/FAME
//1.5:1 - 6,666 gwei/FAME
//1.75:1 - 5,714 gwei/FAME
//2:1 - 5,000 gwei/FAME
//Keep in mind this mechanism is designed to be a fallback to market liquidity. Ideally if the market is healthy, then on
//exchange sites such as OpenSea, or other token exchanges, FAME will trade for normal market value and this contract will be ignored.
//This contract serves a purpose during ramp-up of BattleDrome, to provide a buy-in mechanism, and a sell-off mechanism to distribute
//some of the FAME from ICO backers, to seed initial market distribution, and jump-start new players.
//It also serves a purpose if market liquidity results in poor conditions, provided people are still interested in the tokens/game
//As it will serve as a floor price mechanism, allowing holders to liquidate if there is some demand, and players to buy in if there is supply
//Get the raw sales volume
uint rawSalesVolume = getRecentSalesVolume();
//Find out the minimum sales volume (cost of a diamond chest)
uint minSalesVolume = getBaseValue(ChestType.DIAMOND);
//Raise the sales volume if needed
uint adjustedSalesVolume = (rawSalesVolume<minSalesVolume) ? minSalesVolume : rawSalesVolume;
//Now we figure out our "available balance"
uint availableBalance = getContractFAMEBalance() - calculateCurrentLiability();
//Calculate raw demand ratio
uint rawDemandRatio = (availableBalance * 10000) / adjustedSalesVolume;
//Then clamp the demand ratio within min/max bounds set in constants above
uint demandRatio = (rawDemandRatio<MIN_DEMAND_RATIO)?MIN_DEMAND_RATIO:(rawDemandRatio>MAX_DEMAND_RATIO)?MAX_DEMAND_RATIO:rawDemandRatio;
//And finally calculate the price based on resulting demand ratio
price = (NEW_FAME_ICO_VALUE * 10000) / demandRatio;
}
/**
*@notice Calculate the current price in Ether (wei) for the specified chest type
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@return price The current ETH price (in wei) of a chest of that type
*/
function getPrice(ChestType chestType) public view returns (uint price) {
uint8 discountedPriceMultiplier = uint8(100 - (VOLUME_DISCOUNT_PERCENT * (2**(uint(chestType)-1))));
price = getCurrentFAMEPrice() * getBaseValue(chestType) * discountedPriceMultiplier / 100;
}
/**
*@notice Calculate the Ether Price we will pay to buy back FAME from a user (in Wei)
*@param amount The amount of FAME tokens on offer (the total price returned will be for this full amount)
*@return price The current ETH price (in wei) that will be paid for the full amount specified
*/
function getBuyBackPrice(uint amount) public view returns (uint price) {
//Determine current FAME price, and then we multiply down because our buyback percentage is 90% of current market price
//We also multiply by the amount to find the (perfect world) amount we will pay
price = (getCurrentFAMEPrice() * 9 / 10) * amount;
//Now we determine the max we will pay in a single transaction (capped at 25% of our current holdings in ETH, to prevent abuse)
//This means that if one user tries to dump a large amount to take advantage of a favorable price, they will only be paid a limited amount
//Forcing them to reduce their transaction (or risk being under-paid), and do a second transaction.
uint maxPayout = address(this).balance / 4;
//Next we cap the payout based on the maxPayout:
price = price > maxPayout ? maxPayout : price;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Utility Functions
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@dev Internal Helper Function to determine random roll when opening chests. Crude RNG, should be good enough, but is manipulable by miner theoretically
*@param seedOffset Integer seed offset used for additional randomization
*@return result Random roll from 0-10000 (random percentage to 2 decimal places)
*/
function roll(uint seedOffset) internal view returns (uint16 result) {
uint randomUint = uint(keccak256(abi.encodePacked(block.timestamp,blockhash(block.number),seedOffset)));
result = uint16(randomUint % 10000);
}
/**
*@notice ADMIN FUNCTION: Update the FAME Token ERC1155 Contract Address
*@param newContract The address of the new contract
*/
function setFAMEContractAddress(address newContract) public onlyOwner {
FAMEContract = IERC1155(newContract);
}
/**
*@notice ADMIN FUNCTION: Set the internal Token ID for FAME Tokens within the ERC1155 Contract
*@param id The new Token ID
*/
function setFAMETokenID(uint256 id) public onlyOwner {
FAMETokenID = id;
}
/**
*@notice ADMIN FUNCTION: Update the Warrior NFT ERC1155 Contract Address
*@param newContract The address of the new contract
*/
function setWarriorContractAddress(address newContract) public onlyOwner {
WarriorContract = IWarrior(newContract);
}
/**
*@notice ADMIN FUNCTION: Update the Region NFT ERC1155 Contract Address
*@param newContract The address of the new contract
*/
function setRegionContractAddress(address newContract) public onlyOwner {
RegionContract = IRegion(newContract);
}
/**
*@dev Utility/Helper function for internal use whenever we need to transfer fame between 2 addresses
*@param sender The Sender Address (address from which the FAME will be deducted)
*@param recipient The Recipient Address (address to which the FAME will be credited)
*@param amount The amount of FAME tokens to transfer
*/
function transferFAME(
address sender,
address recipient,
uint256 amount
) internal {
FAMEContract.safeTransferFrom(
sender,
recipient,
FAMETokenID,
amount,
""
);
}
/**
*@notice Fetch the current FAME balance held within the Loot Chest Smart Contract
*@return balance The current FAME Token Balance
*/
function getContractFAMEBalance() public view returns (uint balance) {
return FAMEContract.balanceOf(address(this),FAMETokenID);
}
/**
*@dev Utility/Helper function for internal use, helps determine the worst case liability of a given chest type (amount of FAME that needs paying out)
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@return fame_liability The liability (amount of FAME this countract could potentially be expected to pay out in the worst case, or maximum reward scenario)
*/
function calculateChestLiability(ChestType chestType) internal pure returns (uint fame_liability) {
return getBaseValue(chestType) * 1500 / 1000;
}
/**
*@notice The current total liability of this contract (total FAME that would be required to be paid out if all current chests in circulation contain the max reward)
*@return fame_liability The current total liability (total FAME payout required in worse case from all chests in circulation)
*/
function calculateCurrentLiability() public view returns (uint fame_liability) {
for(uint8 ct=uint8(ChestType.BRONZE);ct<=uint8(ChestType.DIAMOND);ct++)
{
//Get current chest count of chest type
uint chestCount = totalSupply(ct);
//Then multiply by the liability of that chest type
fame_liability += chestCount * calculateChestLiability(ChestType(ct));
}
}
/**
*@notice Checks based on current FAME balance, and current total liability, the max number of specified chestType that can be created safely (factoring in new liability for requested chests)
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@return maxQuantity Maximum quantity of chests of specified type, that can be created safely based on current conditions.
*/
function maxSafeCreatable(ChestType chestType) public view returns (uint maxQuantity) {
maxQuantity = 0;
uint currentLiability = calculateCurrentLiability();
uint currentBalance = getContractFAMEBalance();
if(currentLiability < currentBalance){
uint freeBalance = currentBalance - currentLiability;
maxQuantity = freeBalance / calculateChestLiability(chestType);
}
}
}
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.9;
interface IWarrior {
function mintCustomWarrior(address owner, uint32 generation, bool special, uint randomSeed, uint16 colorHue, uint8 armorType, uint8 shieldType, uint8 weaponType) external returns(uint theNewWarrior);
function newWarrior() external returns(uint theNewWarrior);
function getWarriorIDByName(string calldata name) external view returns(uint);
function nameExists(string calldata _name) external view returns(bool);
function setName(uint warriorID, string calldata name) external;
function ownerOf(uint _id) external view returns(address);
function getWarriorCost() external pure returns(uint);
function getWarriorName(uint warriorID) external view returns(string memory);
function payWarrior(uint warriorID, uint amount, bool tax) external;
function transferFAMEFromWarriorToWarrior(uint senderID, uint recipientID, uint amount, bool tax) external;
function transferFAMEFromWarriorToAddress(uint warriorID, address recipient, uint amount) external;
}
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
interface IRegion is IERC1155 {
function trustedCreateRegion() external returns (uint256 theNewRegion);
function newRegion() external returns (uint256 theNewRegion);
function getCurrentRegionCount() external view returns (uint256);
function getCurrentRegionPricingCounter() external view returns (uint256);
function ownerOf(uint256 _id) external view returns (address);
function getRegionCost(int256 offset) external view returns (uint256);
function getRegionName(uint256 regionID) external;
function payRegion(uint256 regionID, uint256 amount, bool tax) external;
}
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.9;
//import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
//import 'multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol';
//import 'multi-token-standard/contracts/tokens/ERC1155/ERC1155Metadata.sol';
//import 'multi-token-standard/contracts/tokens/ERC1155/ERC1155MintBurn.sol';
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/presets/ERC1155PresetMinterPauser.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title BDERC1155Tradable
* BDERC1155Tradable - BattleDrome ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
contract BDERC1155Tradable is ERC1155PresetMinterPauser, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping(uint256 => address) public creators;
mapping(uint256 => uint256) public tokenSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
//Metadata URI (for backwards compat with old code, overrides URI functionality from openzeppelin)
string public baseMetadataURI;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(
creators[_id] == msg.sender,
"ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED"
);
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(
balanceOf(msg.sender, _id) > 0,
"ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED"
);
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress,
string memory _metadataURI
) ERC1155PresetMinterPauser(_metadataURI) {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
_setBaseMetadataURI(_metadataURI);
}
function uri(uint256 _id) public view override returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return string(abi.encodePacked(baseMetadataURI, Strings.toString(_id)));
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(uint256 _id) public view returns (uint256) {
return tokenSupply[_id];
}
function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal {
baseMetadataURI = _newBaseMetadataURI;
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(string memory _newBaseMetadataURI)
public
onlyOwner
{
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public override creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id] + _quantity;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(
creators[_id] == msg.sender,
"ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED"
);
uint256 quantity = _quantities[i];
tokenSupply[_id] = tokenSupply[_id] + quantity;
}
_mintBatch(_to, _ids, _quantities, _data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal override {
tokenSupply[id] = tokenSupply[id] - amount;
super._burn(from,id,amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal override {
for (uint256 i = 0; i < ids.length; i++) {
tokenSupply[ids[i]] = tokenSupply[ids[i]] - amounts[i];
}
super._burnBatch(from,ids,amounts);
}
/**
* @dev Change the creator address for given tokens
* @param _to Address of the new creator
* @param _ids Array of Token IDs to change creator
*/
function setCreator(address _to, uint256[] memory _ids) public {
require(
_to != address(0),
"ERC1155Tradable#setCreator: INVALID_ADDRESS."
);
require(
_ids.length>0,
"ERC1155Tradeable#setCreator: EMPTY_ARRAY"
);
for (uint256 i = 0; i < _ids.length; i++) {
uint256 id = _ids[i];
_setCreator(_to, id);
}
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(address _owner, address _operator)
public
view
override
returns (bool isOperator)
{
//TODO: FAILING HERE ON REGION SALE
//Failing from inside the transferFAME function (inside safeTransferFrom in the FAME contract itself)
//When being called by the Region contract as the operator
//With the user being the owner.
//WHY!?!?!?
//Ideas:
// Look into the proxy contract, this code is throwing a revert and the debugger seems non-specific
// Pour over this again with debugger a couple times
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Change the creator address for given token
* @param _to Address of the new creator
* @param _id Token IDs to change creator of
*/
function _setCreator(address _to, uint256 _id) internal creatorOnly(_id) {
creators[_id] = _to;
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 _id) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() internal view returns (uint256) {
return _currentTokenID + 1;
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() internal {
_currentTokenID++;
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1155.sol";
import "../extensions/ERC1155Burnable.sol";
import "../extensions/ERC1155Pausable.sol";
import "../../../access/AccessControlEnumerable.sol";
import "../../../utils/Context.sol";
/**
* @dev {ERC1155} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC1155PresetMinterPauser is Context, AccessControlEnumerable, ERC1155Burnable, ERC1155Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that
* deploys the contract.
*/
constructor(string memory uri) ERC1155(uri) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`, of token type `id`.
*
* See {ERC1155-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mint(to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
*/
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mintBatch(to, ids, amounts, data);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerable, ERC1155)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override(ERC1155, ERC1155Pausable) {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1155.sol";
import "../../../security/Pausable.sol";
/**
* @dev ERC1155 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*
* _Available since v3.1._
*/
abstract contract ERC1155Pausable is ERC1155, Pausable {
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1155.sol";
/**
* @dev Extension of {ERC1155} that allows token holders to destroy both their
* own tokens and those that they have been approved to use.
*
* _Available since v3.1._
*/
abstract contract ERC1155Burnable is ERC1155 {
function burn(
address account,
uint256 id,
uint256 value
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burn(account, id, value);
}
function burnBatch(
address account,
uint256[] memory ids,
uint256[] memory values
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burnBatch(account, ids, values);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
} | 2% - Bronze, 4% - Silver, 8% - Gold, 16% - Diamond
| uint constant CHANCE_BONUS_25 = 200; | 13,683,455 | [
1,
22,
9,
300,
605,
1949,
8489,
16,
4202,
1059,
9,
300,
348,
330,
502,
16,
565,
1725,
9,
300,
611,
1673,
16,
1377,
2872,
9,
300,
12508,
301,
1434,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5381,
6469,
4722,
67,
38,
673,
3378,
67,
2947,
4202,
273,
4044,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/11297108099/0x4C7E1e1Ba5e35934C8323d75AF838fDa26588177/sources/contracts/PBAB_Collabs/GenArt721CoreV2_PBAB.sol | * @notice Updates name of project `_projectId` to be `_projectName`./ | function updateProjectName(uint256 _projectId, string memory _projectName)
public
onlyUnlocked(_projectId)
onlyArtistOrWhitelisted(_projectId)
{
projects[_projectId].name = _projectName;
}
| 11,034,262 | [
1,
5121,
508,
434,
1984,
1375,
67,
4406,
548,
68,
358,
506,
1375,
67,
4406,
461,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
4109,
461,
12,
11890,
5034,
389,
4406,
548,
16,
533,
3778,
389,
4406,
461,
13,
203,
3639,
1071,
203,
3639,
1338,
7087,
329,
24899,
4406,
548,
13,
203,
3639,
1338,
4411,
376,
1162,
18927,
329,
24899,
4406,
548,
13,
203,
565,
288,
203,
3639,
10137,
63,
67,
4406,
548,
8009,
529,
273,
389,
4406,
461,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
_____ _________________ _ _ _ ___ _
/ ___| ___| ___ \ ___ \ | | | | / / | | |
\ `--.| |__ | |_/ / |_/ / | | | |/ /| | | |
`--. \ __|| __/| __/| | | | \| | | |
/\__/ / |___| | | | | |_| | |\ \ |_| |
\____/\____/\_| \_| \___/\_| \_/\___/
seppuku.me
t.me/seppukume
twitter.com/SeppukuMe
Stake your Uniswap LP tokens to Earn Seppuku
*/
pragma solidity ^0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity 0.6.12;
contract SEPPUKUToken is ERC20("Seppuku.me", "SEPPUKU"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
}
}
// File: contracts/MasterChef.sol
pragma solidity 0.6.12;
// MasterChef is the master of SEPPUKU. He can make SEPPUKU and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SEPPUKU is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SEPPUKU to distribute per block.
uint256 lastRewardBlock; // Last block number that SEPPUKU distribution occurs.
uint256 accSEPPUKUPerShare; // Accumulated SEPPUKU per share, times 1e12. See below.
}
// The SEPPUKU TOKEN!
SEPPUKUToken public SEPPUKU;
// Dev address.
address public devaddr;
// Block number when bonus SEPPUKU period ends.
uint256 public bonusEndBlock;
// SEPPUKU tokens created per block.
uint256 public SEPPUKUPerBlock;
// Bonus muliplier for early SEPPUKU makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSSEPPUKUHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SEPPUKUToken _SEPPUKU,
address _devaddr,
uint256 _SEPPUKUPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
SEPPUKU = _SEPPUKU;
devaddr = _devaddr;
SEPPUKUPerBlock = _SEPPUKUPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSEPPUKUPerShare: 0
}));
}
// Update the given pool's SEPPUKU allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending SEPPUKU on frontend.
function pendingSEPPUKU(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSEPPUKUPerShare = pool.accSEPPUKUPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 SEPPUKUReward = multiplier.mul(SEPPUKUPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSEPPUKUPerShare = accSEPPUKUPerShare.add(SEPPUKUReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSEPPUKUPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function mint(uint256 amount) public onlyOwner{
SEPPUKU.mint(devaddr, amount);
}
// Update reward variables of the given pool to be up-to-date.
function burn(uint256 amount) public onlyOwner{
SEPPUKU.burn(amount);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 SEPPUKUReward = multiplier.mul(SEPPUKUPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
SEPPUKU.mint(devaddr, SEPPUKUReward.div(4));
SEPPUKU.mint(address(this), SEPPUKUReward);
pool.accSEPPUKUPerShare = pool.accSEPPUKUPerShare.add(SEPPUKUReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SEPPUKU allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSEPPUKUPerShare).div(1e12).sub(user.rewardDebt);
safeSEPPUKUTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSEPPUKUPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSEPPUKUPerShare).div(1e12).sub(user.rewardDebt);
safeSEPPUKUTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSEPPUKUPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe SEPPUKU transfer function, just in case if rounding error causes pool to not have enough SEPPUKU.
function safeSEPPUKUTransfer(address _to, uint256 _amount) internal {
uint256 SEPPUKUBal = SEPPUKU.balanceOf(address(this));
if (_amount > SEPPUKUBal) {
SEPPUKU.transfer(_to, SEPPUKUBal);
} else {
SEPPUKU.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | Update reward variables of the given pool to be up-to-date. | function mint(uint256 amount) public onlyOwner{
SEPPUKU.mint(devaddr, amount);
}
| 7,669,543 | [
1,
1891,
19890,
3152,
434,
326,
864,
2845,
358,
506,
731,
17,
869,
17,
712,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
12,
11890,
5034,
3844,
13,
1071,
1338,
5541,
95,
203,
3639,
3174,
6584,
57,
47,
57,
18,
81,
474,
12,
5206,
4793,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x86A1Ba68cA53e68D49E0D9ec9007ceB06A078F07/sources/BALC.sol | * @dev Casts the address to uint256 without masking./ | function _addressToUint256(address value) private pure returns (uint256 result) {
assembly {
result := value
}
}
| 3,699,939 | [
1,
9735,
87,
326,
1758,
358,
2254,
5034,
2887,
3066,
310,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
2867,
774,
5487,
5034,
12,
2867,
460,
13,
3238,
16618,
1135,
261,
11890,
5034,
563,
13,
288,
203,
3639,
19931,
288,
203,
2088,
519,
460,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xB5505Ca8bE7aCd405325DbdA7f21F4F09222Ebd4/sources/src/clones/ERC721ACloneable.sol | * Returns the packed ownership data of `tokenId`./ If not burned. Invariant: There will always be an initialized ownership slot (i.e. `ownership.addr != address(0) && ownership.burned == false`) before an unintialized ownership slot (i.e. `ownership.addr == address(0) && ownership.burned == false`) Hence, `curr` will not underflow. We can directly compare the packed value. If the address is zero, packed will be zero. | function _packedOwnershipOf(uint256 tokenId)
private
view
returns (uint256)
{
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr) {
if (curr < _currentIndex) {
uint256 packed = _packedOwnerships[curr];
if (packed & _BITMASK_BURNED == 0) {
while (packed == 0) {
packed = _packedOwnerships[--curr];
}
return packed;
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
| 15,605,279 | [
1,
1356,
326,
12456,
23178,
501,
434,
1375,
2316,
548,
8338,
19,
971,
486,
18305,
329,
18,
657,
8688,
30,
6149,
903,
3712,
506,
392,
6454,
23178,
4694,
261,
77,
18,
73,
18,
1375,
995,
12565,
18,
4793,
480,
1758,
12,
20,
13,
597,
23178,
18,
70,
321,
329,
422,
629,
24065,
1865,
392,
640,
474,
649,
1235,
23178,
4694,
261,
77,
18,
73,
18,
1375,
995,
12565,
18,
4793,
422,
1758,
12,
20,
13,
597,
23178,
18,
70,
321,
329,
422,
629,
24065,
670,
802,
16,
1375,
17016,
68,
903,
486,
3613,
2426,
18,
1660,
848,
5122,
3400,
326,
12456,
460,
18,
971,
326,
1758,
353,
3634,
16,
12456,
903,
506,
3634,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
2920,
329,
5460,
12565,
951,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
3238,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2254,
5034,
4306,
273,
1147,
548,
31,
203,
203,
3639,
22893,
288,
203,
5411,
309,
261,
67,
1937,
1345,
548,
1435,
1648,
4306,
13,
288,
203,
7734,
309,
261,
17016,
411,
389,
2972,
1016,
13,
288,
203,
10792,
2254,
5034,
12456,
273,
389,
2920,
329,
5460,
12565,
87,
63,
17016,
15533,
203,
10792,
309,
261,
2920,
329,
473,
389,
15650,
11704,
67,
38,
8521,
2056,
422,
374,
13,
288,
203,
13491,
1323,
261,
2920,
329,
422,
374,
13,
288,
203,
18701,
12456,
273,
389,
2920,
329,
5460,
12565,
87,
63,
413,
17016,
15533,
203,
13491,
289,
203,
13491,
327,
12456,
31,
203,
10792,
289,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
3639,
15226,
16837,
1138,
1290,
3989,
19041,
1345,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./SafeMath.sol";
import "./HoldefiPausableOwnable.sol";
import "./HoldefiCollaterals.sol";
/// @notice File: contracts/HoldefiPrices.sol
interface HoldefiPricesInterface {
function getAssetValueFromAmount(address asset, uint256 amount) external view returns(uint256 value);
function getAssetAmountFromValue(address asset, uint256 value) external view returns(uint256 amount);
}
/// @notice File: contracts/HoldefiSettings.sol
interface HoldefiSettingsInterface {
/// @notice Markets Features
struct MarketSettings {
bool isExist;
bool isActive;
uint256 borrowRate;
uint256 borrowRateUpdateTime;
uint256 suppliersShareRate;
uint256 suppliersShareRateUpdateTime;
uint256 promotionRate;
}
/// @notice Collateral Features
struct CollateralSettings {
bool isExist;
bool isActive;
uint256 valueToLoanRate;
uint256 VTLUpdateTime;
uint256 penaltyRate;
uint256 penaltyUpdateTime;
uint256 bonusRate;
}
function getInterests(address market)
external
view
returns (uint256 borrowRate, uint256 supplyRateBase, uint256 promotionRate);
function resetPromotionRate (address market) external;
function getMarketsList() external view returns(address[] memory marketsList);
function marketAssets(address market) external view returns(MarketSettings memory);
function collateralAssets(address collateral) external view returns(CollateralSettings memory);
}
/// @title Main Holdefi contract
/// @author Holdefi Team
/// @dev The address of ETH considered as 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
/// @dev All indexes are scaled by (secondsPerYear * rateDecimals)
/// @dev All values are based ETH price considered 1 and all values decimals considered 30
contract Holdefi is HoldefiPausableOwnable {
using SafeMath for uint256;
/// @notice Markets are assets can be supplied and borrowed
struct Market {
uint256 totalSupply;
uint256 supplyIndex; // Scaled by: secondsPerYear * rateDecimals
uint256 supplyIndexUpdateTime;
uint256 totalBorrow;
uint256 borrowIndex; // Scaled by: secondsPerYear * rateDecimals
uint256 borrowIndexUpdateTime;
uint256 promotionReserveScaled; // Scaled by: secondsPerYear * rateDecimals
uint256 promotionReserveLastUpdateTime;
uint256 promotionDebtScaled; // Scaled by: secondsPerYear * rateDecimals
uint256 promotionDebtLastUpdateTime;
}
/// @notice Collaterals are assets can be used only as collateral for borrowing with no interest
struct Collateral {
uint256 totalCollateral;
uint256 totalLiquidatedCollateral;
}
/// @notice Users profile for each market
struct MarketAccount {
mapping (address => uint) allowance;
uint256 balance;
uint256 accumulatedInterest;
uint256 lastInterestIndex; // Scaled by: secondsPerYear * rateDecimals
}
/// @notice Users profile for each collateral
struct CollateralAccount {
mapping (address => uint) allowance;
uint256 balance;
uint256 lastUpdateTime;
}
struct MarketData {
uint256 balance;
uint256 interest;
uint256 currentIndex;
}
address constant public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice All rates in this contract are scaled by rateDecimals
uint256 constant public rateDecimals = 10 ** 4;
uint256 constant public secondsPerYear = 31536000;
/// @dev For round up borrow interests
uint256 constant private oneUnit = 1;
/// @dev Used for calculating liquidation threshold
/// @dev There is 5% gap between value to loan rate and liquidation rate
uint256 constant private fivePercentLiquidationGap = 500;
/// @notice Contract for getting protocol settings
HoldefiSettingsInterface public holdefiSettings;
/// @notice Contract for getting asset prices
HoldefiPricesInterface public holdefiPrices;
/// @notice Contract for holding collaterals
HoldefiCollaterals public holdefiCollaterals;
/// @dev Markets: marketAddress => marketDetails
mapping (address => Market) public marketAssets;
/// @dev Collaterals: collateralAddress => collateralDetails
mapping (address => Collateral) public collateralAssets;
/// @dev Markets Debt after liquidation: collateralAddress => marketAddress => marketDebtBalance
mapping (address => mapping (address => uint)) public marketDebt;
/// @dev Users Supplies: userAddress => marketAddress => supplyDetails
mapping (address => mapping (address => MarketAccount)) private supplies;
/// @dev Users Borrows: userAddress => collateralAddress => marketAddress => borrowDetails
mapping (address => mapping (address => mapping (address => MarketAccount))) private borrows;
/// @dev Users Collaterals: userAddress => collateralAddress => collateralDetails
mapping (address => mapping (address => CollateralAccount)) private collaterals;
// ----------- Events -----------
/// @notice Event emitted when a market asset is supplied
event Supply(
address sender,
address indexed supplier,
address indexed market,
uint256 amount,
uint256 balance,
uint256 interest,
uint256 index,
uint16 referralCode
);
/// @notice Event emitted when a supply is withdrawn
event WithdrawSupply(
address sender,
address indexed supplier,
address indexed market,
uint256 amount,
uint256 balance,
uint256 interest,
uint256 index
);
/// @notice Event emitted when a collateral asset is deposited
event Collateralize(
address sender,
address indexed collateralizer,
address indexed collateral,
uint256 amount,
uint256 balance
);
/// @notice Event emitted when a collateral is withdrawn
event WithdrawCollateral(
address sender,
address indexed collateralizer,
address indexed collateral,
uint256 amount,
uint256 balance
);
/// @notice Event emitted when a market asset is borrowed
event Borrow(
address sender,
address indexed borrower,
address indexed market,
address indexed collateral,
uint256 amount,
uint256 balance,
uint256 interest,
uint256 index,
uint16 referralCode
);
/// @notice Event emitted when a borrow is repaid
event RepayBorrow(
address sender,
address indexed borrower,
address indexed market,
address indexed collateral,
uint256 amount,
uint256 balance,
uint256 interest,
uint256 index
);
/// @notice Event emitted when the supply index is updated for a market asset
event UpdateSupplyIndex(address indexed market, uint256 newSupplyIndex, uint256 supplyRate);
/// @notice Event emitted when the borrow index is updated for a market asset
event UpdateBorrowIndex(address indexed market, uint256 newBorrowIndex);
/// @notice Event emitted when a collateral is liquidated
event CollateralLiquidated(
address indexed borrower,
address indexed market,
address indexed collateral,
uint256 marketDebt,
uint256 liquidatedCollateral
);
/// @notice Event emitted when a liquidated collateral is purchased in exchange for the specified market
event BuyLiquidatedCollateral(
address indexed market,
address indexed collateral,
uint256 marketAmount,
uint256 collateralAmount
);
/// @notice Event emitted when HoldefiPrices contract is changed
event HoldefiPricesContractChanged(address newAddress, address oldAddress);
/// @notice Event emitted when a liquidation reserve is withdrawn by the owner
event LiquidationReserveWithdrawn(address indexed collateral, uint256 amount);
/// @notice Event emitted when a liquidation reserve is deposited
event LiquidationReserveDeposited(address indexed collateral, uint256 amount);
/// @notice Event emitted when a promotion reserve is withdrawn by the owner
event PromotionReserveWithdrawn(address indexed market, uint256 amount);
/// @notice Event emitted when a promotion reserve is deposited
event PromotionReserveDeposited(address indexed market, uint256 amount);
/// @notice Event emitted when a promotion reserve is updated
event PromotionReserveUpdated(address indexed market, uint256 promotionReserve);
/// @notice Event emitted when a promotion debt is updated
event PromotionDebtUpdated(address indexed market, uint256 promotionDebt);
/// @notice Initializes the Holdefi contract
/// @param holdefiSettingsAddress Holdefi settings contract address
/// @param holdefiPricesAddress Holdefi prices contract address
constructor(
HoldefiSettingsInterface holdefiSettingsAddress,
HoldefiPricesInterface holdefiPricesAddress
)
public
{
holdefiSettings = holdefiSettingsAddress;
holdefiPrices = holdefiPricesAddress;
holdefiCollaterals = new HoldefiCollaterals();
}
/// @dev Modifier to check if the asset is ETH or not
/// @param asset Address of the given asset
modifier isNotETHAddress(address asset) {
require (asset != ethAddress, "Asset should not be ETH address");
_;
}
/// @dev Modifier to check if the market is active or not
/// @param market Address of the given market
modifier marketIsActive(address market) {
require (holdefiSettings.marketAssets(market).isActive, "Market is not active");
_;
}
/// @dev Modifier to check if the collateral is active or not
/// @param collateral Address of the given collateral
modifier collateralIsActive(address collateral) {
require (holdefiSettings.collateralAssets(collateral).isActive, "Collateral is not active");
_;
}
/// @dev Modifier to check if the account address is equal to the msg.sender or not
/// @param account The given account address
modifier accountIsValid(address account) {
require (msg.sender != account, "Account is not valid");
_;
}
receive() external payable {
revert();
}
/// @notice Returns balance and interest of an account for a given market
/// @dev supplyInterest = accumulatedInterest + (balance * (marketSupplyIndex - userLastSupplyInterestIndex))
/// @param account Supplier address to get supply information
/// @param market Address of the given market
/// @return balance Supplied amount on the specified market
/// @return interest Profit earned
/// @return currentSupplyIndex Supply index for the given market at current time
function getAccountSupply(address account, address market)
public
view
returns (uint256 balance, uint256 interest, uint256 currentSupplyIndex)
{
balance = supplies[account][market].balance;
(currentSupplyIndex,,) = getCurrentSupplyIndex(market);
uint256 deltaInterestIndex = currentSupplyIndex.sub(supplies[account][market].lastInterestIndex);
uint256 deltaInterestScaled = deltaInterestIndex.mul(balance);
uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals);
interest = supplies[account][market].accumulatedInterest.add(deltaInterest);
}
/// @notice Returns balance and interest of an account for a given market on a given collateral
/// @dev borrowInterest = accumulatedInterest + (balance * (marketBorrowIndex - userLastBorrowInterestIndex))
/// @param account Borrower address to get Borrow information
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @return balance Borrowed amount on the specified market
/// @return interest The amount of interest the borrower should pay
/// @return currentBorrowIndex Borrow index for the given market at current time
function getAccountBorrow(address account, address market, address collateral)
public
view
returns (uint256 balance, uint256 interest, uint256 currentBorrowIndex)
{
balance = borrows[account][collateral][market].balance;
(currentBorrowIndex,,) = getCurrentBorrowIndex(market);
uint256 deltaInterestIndex =
currentBorrowIndex.sub(borrows[account][collateral][market].lastInterestIndex);
uint256 deltaInterestScaled = deltaInterestIndex.mul(balance);
uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals);
if (balance > 0) {
deltaInterest = deltaInterest.add(oneUnit);
}
interest = borrows[account][collateral][market].accumulatedInterest.add(deltaInterest);
}
/// @notice Returns collateral balance, time since last activity, borrow power, total borrow value, and liquidation status for a given collateral
/// @dev borrowPower = (collateralValue / collateralValueToLoanRate) - totalBorrowValue
/// @dev liquidationThreshold = collateralValueToLoanRate - 5%
/// @dev User will be in liquidation state if (collateralValue / totalBorrowValue) < liquidationThreshold
/// @param account Account address to get collateral information
/// @param collateral Address of the given collateral
/// @return balance Amount of the specified collateral
/// @return timeSinceLastActivity Time since last activity performed by the account
/// @return borrowPowerValue The borrowing power for the account of the given collateral
/// @return totalBorrowValue Accumulative borrowed values on the given collateral
/// @return underCollateral A boolean value indicates whether the user is in the liquidation state or not
function getAccountCollateral(address account, address collateral)
public
view
returns (
uint256 balance,
uint256 timeSinceLastActivity,
uint256 borrowPowerValue,
uint256 totalBorrowValue,
bool underCollateral
)
{
uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate;
if (valueToLoanRate == 0) {
return (0, 0, 0, 0, false);
}
balance = collaterals[account][collateral].balance;
uint256 collateralValue = holdefiPrices.getAssetValueFromAmount(collateral, balance);
uint256 liquidationThresholdRate = valueToLoanRate.sub(fivePercentLiquidationGap);
uint256 totalBorrowPowerValue = collateralValue.mul(rateDecimals).div(valueToLoanRate);
uint256 liquidationThresholdValue = collateralValue.mul(rateDecimals).div(liquidationThresholdRate);
totalBorrowValue = getAccountTotalBorrowValue(account, collateral);
if (totalBorrowValue > 0) {
timeSinceLastActivity = block.timestamp.sub(collaterals[account][collateral].lastUpdateTime);
}
borrowPowerValue = 0;
if (totalBorrowValue < totalBorrowPowerValue) {
borrowPowerValue = totalBorrowPowerValue.sub(totalBorrowValue);
}
underCollateral = false;
if (totalBorrowValue > liquidationThresholdValue) {
underCollateral = true;
}
}
/// @notice Returns maximum amount spender can withdraw from account supplies on a given market
/// @param account Supplier address
/// @param spender Spender address
/// @param market Address of the given market
/// @return res Maximum amount spender can withdraw from account supplies on a given market
function getAccountWithdrawSupplyAllowance (address account, address spender, address market)
external
view
returns (uint256 res)
{
res = supplies[account][market].allowance[spender];
}
/// @notice Returns maximum amount spender can withdraw from account balance on a given collateral
/// @param account Account address
/// @param spender Spender address
/// @param collateral Address of the given collateral
/// @return res Maximum amount spender can withdraw from account balance on a given collateral
function getAccountWithdrawCollateralAllowance (
address account,
address spender,
address collateral
)
external
view
returns (uint256 res)
{
res = collaterals[account][collateral].allowance[spender];
}
/// @notice Returns maximum amount spender can withdraw from account borrows on a given market based on a given collteral
/// @param account Borrower address
/// @param spender Spender address
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @return res Maximum amount spender can withdraw from account borrows on a given market based on a given collteral
function getAccountBorrowAllowance (
address account,
address spender,
address market,
address collateral
)
external
view
returns (uint256 res)
{
res = borrows[account][collateral][market].allowance[spender];
}
/// @notice Returns total borrow value of an account based on a given collateral
/// @param account Account address
/// @param collateral Address of the given collateral
/// @return totalBorrowValue Accumulative borrowed values on the given collateral
function getAccountTotalBorrowValue (address account, address collateral)
public
view
returns (uint256 totalBorrowValue)
{
MarketData memory borrowData;
address market;
uint256 totalDebt;
uint256 assetValue;
totalBorrowValue = 0;
address[] memory marketsList = holdefiSettings.getMarketsList();
for (uint256 i = 0 ; i < marketsList.length ; i++) {
market = marketsList[i];
(borrowData.balance, borrowData.interest,) = getAccountBorrow(account, market, collateral);
totalDebt = borrowData.balance.add(borrowData.interest);
assetValue = holdefiPrices.getAssetValueFromAmount(market, totalDebt);
totalBorrowValue = totalBorrowValue.add(assetValue);
}
}
/// @notice The collateral reserve amount for buying liquidated collateral
/// @param collateral Address of the given collateral
/// @return reserve Liquidation reserves for the given collateral
function getLiquidationReserve (address collateral) public view returns(uint256 reserve) {
address market;
uint256 assetValue;
uint256 totalDebtValue = 0;
address[] memory marketsList = holdefiSettings.getMarketsList();
for (uint256 i = 0 ; i < marketsList.length ; i++) {
market = marketsList[i];
assetValue = holdefiPrices.getAssetValueFromAmount(market, marketDebt[collateral][market]);
totalDebtValue = totalDebtValue.add(assetValue);
}
uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate;
uint256 totalDebtCollateralValue = totalDebtValue.mul(bonusRate).div(rateDecimals);
uint256 liquidatedCollateralNeeded = holdefiPrices.getAssetAmountFromValue(
collateral,
totalDebtCollateralValue
);
reserve = 0;
uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral;
if (totalLiquidatedCollateral > liquidatedCollateralNeeded) {
reserve = totalLiquidatedCollateral.sub(liquidatedCollateralNeeded);
}
}
/// @notice Returns the amount of discounted collateral can be bought in exchange for the amount of a given market
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @param marketAmount The amount of market should be paid
/// @return collateralAmountWithDiscount Amount of discounted collateral can be bought
function getDiscountedCollateralAmount (address market, address collateral, uint256 marketAmount)
public
view
returns (uint256 collateralAmountWithDiscount)
{
uint256 marketValue = holdefiPrices.getAssetValueFromAmount(market, marketAmount);
uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate;
uint256 collateralValue = marketValue.mul(bonusRate).div(rateDecimals);
collateralAmountWithDiscount = holdefiPrices.getAssetAmountFromValue(collateral, collateralValue);
}
/// @notice Returns supply index and supply rate for a given market at current time
/// @dev newSupplyIndex = oldSupplyIndex + (deltaTime * supplyRate)
/// @param market Address of the given market
/// @return supplyIndex Supply index of the given market
/// @return supplyRate Supply rate of the given market
/// @return currentTime Current block timestamp
function getCurrentSupplyIndex (address market)
public
view
returns (
uint256 supplyIndex,
uint256 supplyRate,
uint256 currentTime
)
{
(, uint256 supplyRateBase, uint256 promotionRate) = holdefiSettings.getInterests(market);
currentTime = block.timestamp;
uint256 deltaTimeSupply = currentTime.sub(marketAssets[market].supplyIndexUpdateTime);
supplyRate = supplyRateBase.add(promotionRate);
uint256 deltaTimeInterest = deltaTimeSupply.mul(supplyRate);
supplyIndex = marketAssets[market].supplyIndex.add(deltaTimeInterest);
}
/// @notice Returns borrow index and borrow rate for the given market at current time
/// @dev newBorrowIndex = oldBorrowIndex + (deltaTime * borrowRate)
/// @param market Address of the given market
/// @return borrowIndex Borrow index of the given market
/// @return borrowRate Borrow rate of the given market
/// @return currentTime Current block timestamp
function getCurrentBorrowIndex (address market)
public
view
returns (
uint256 borrowIndex,
uint256 borrowRate,
uint256 currentTime
)
{
borrowRate = holdefiSettings.marketAssets(market).borrowRate;
currentTime = block.timestamp;
uint256 deltaTimeBorrow = currentTime.sub(marketAssets[market].borrowIndexUpdateTime);
uint256 deltaTimeInterest = deltaTimeBorrow.mul(borrowRate);
borrowIndex = marketAssets[market].borrowIndex.add(deltaTimeInterest);
}
/// @notice Returns promotion reserve for a given market at current time
/// @dev promotionReserveScaled is scaled by (secondsPerYear * rateDecimals)
/// @param market Address of the given market
/// @return promotionReserveScaled Promotion reserve of the given market
/// @return currentTime Current block timestamp
function getPromotionReserve (address market)
public
view
returns (uint256 promotionReserveScaled, uint256 currentTime)
{
(uint256 borrowRate, uint256 supplyRateBase,) = holdefiSettings.getInterests(market);
currentTime = block.timestamp;
uint256 allSupplyInterest = marketAssets[market].totalSupply.mul(supplyRateBase);
uint256 allBorrowInterest = marketAssets[market].totalBorrow.mul(borrowRate);
uint256 deltaTime = currentTime.sub(marketAssets[market].promotionReserveLastUpdateTime);
uint256 currentInterest = allBorrowInterest.sub(allSupplyInterest);
uint256 deltaTimeInterest = currentInterest.mul(deltaTime);
promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(deltaTimeInterest);
}
/// @notice Returns promotion debt for a given market at current time
/// @dev promotionDebtScaled is scaled by secondsPerYear * rateDecimals
/// @param market Address of the given market
/// @return promotionDebtScaled Promotion debt of the given market
/// @return currentTime Current block timestamp
function getPromotionDebt (address market)
public
view
returns (uint256 promotionDebtScaled, uint256 currentTime)
{
uint256 promotionRate = holdefiSettings.marketAssets(market).promotionRate;
currentTime = block.timestamp;
promotionDebtScaled = marketAssets[market].promotionDebtScaled;
if (promotionRate != 0) {
uint256 deltaTime = block.timestamp.sub(marketAssets[market].promotionDebtLastUpdateTime);
uint256 currentInterest = marketAssets[market].totalSupply.mul(promotionRate);
uint256 deltaTimeInterest = currentInterest.mul(deltaTime);
promotionDebtScaled = promotionDebtScaled.add(deltaTimeInterest);
}
}
/// @notice Update a market supply index, promotion reserve, and promotion debt
/// @param market Address of the given market
function beforeChangeSupplyRate (address market) public {
updateSupplyIndex(market);
updatePromotionReserve(market);
updatePromotionDebt(market);
}
/// @notice Update a market borrow index, supply index, promotion reserve, and promotion debt
/// @param market Address of the given market
function beforeChangeBorrowRate (address market) external {
updateBorrowIndex(market);
beforeChangeSupplyRate(market);
}
/// @notice Deposit ERC20 asset for supplying
/// @param market Address of the given market
/// @param amount The amount of asset supplier supplies
/// @param referralCode A unique code used as an identifier of referrer
function supply(address market, uint256 amount, uint16 referralCode)
external
isNotETHAddress(market)
{
supplyInternal(msg.sender, market, amount, referralCode);
}
/// @notice Deposit ETH for supplying
/// @notice msg.value The amount of asset supplier supplies
/// @param referralCode A unique code used as an identifier of referrer
function supply(uint16 referralCode) external payable {
supplyInternal(msg.sender, ethAddress, msg.value, referralCode);
}
/// @notice Sender deposits ERC20 asset belonging to the supplier
/// @param account Address of the supplier
/// @param market Address of the given market
/// @param amount The amount of asset supplier supplies
/// @param referralCode A unique code used as an identifier of referrer
function supplyBehalf(address account, address market, uint256 amount, uint16 referralCode)
external
isNotETHAddress(market)
{
supplyInternal(account, market, amount, referralCode);
}
/// @notice Sender deposits ETH belonging to the supplier
/// @notice msg.value The amount of ETH sender deposits belonging to the supplier
/// @param account Address of the supplier
/// @param referralCode A unique code used as an identifier of referrer
function supplyBehalf(address account, uint16 referralCode)
external
payable
{
supplyInternal(account, ethAddress, msg.value, referralCode);
}
/// @notice Sender approves of the withdarawl for the account in the market asset
/// @param account Address of the account allowed to withdrawn
/// @param market Address of the given market
/// @param amount The amount is allowed to withdrawn
function approveWithdrawSupply(address account, address market, uint256 amount)
external
accountIsValid(account)
marketIsActive(market)
{
supplies[msg.sender][market].allowance[account] = amount;
}
/// @notice Withdraw supply of a given market
/// @param market Address of the given market
/// @param amount The amount will be withdrawn from the market
function withdrawSupply(address market, uint256 amount)
external
{
withdrawSupplyInternal(msg.sender, market, amount);
}
/// @notice Sender withdraws supply belonging to the supplier
/// @param account Address of the supplier
/// @param market Address of the given market
/// @param amount The amount will be withdrawn from the market
function withdrawSupplyBehalf(address account, address market, uint256 amount) external {
uint256 allowance = supplies[account][market].allowance[msg.sender];
require(
amount <= allowance,
"Withdraw not allowed"
);
supplies[account][market].allowance[msg.sender] = allowance.sub(amount);
withdrawSupplyInternal(account, market, amount);
}
/// @notice Deposit ERC20 asset as a collateral
/// @param collateral Address of the given collateral
/// @param amount The amount will be collateralized
function collateralize (address collateral, uint256 amount)
external
isNotETHAddress(collateral)
{
collateralizeInternal(msg.sender, collateral, amount);
}
/// @notice Deposit ETH as a collateral
/// @notice msg.value The amount of ETH will be collateralized
function collateralize () external payable {
collateralizeInternal(msg.sender, ethAddress, msg.value);
}
/// @notice Sender deposits ERC20 asset as a collateral belonging to the user
/// @param account Address of the user
/// @param collateral Address of the given collateral
/// @param amount The amount will be collateralized
function collateralizeBehalf (address account, address collateral, uint256 amount)
external
isNotETHAddress(collateral)
{
collateralizeInternal(account, collateral, amount);
}
/// @notice Sender deposits ETH as a collateral belonging to the user
/// @notice msg.value The amount of ETH Sender deposits as a collateral belonging to the user
/// @param account Address of the user
function collateralizeBehalf (address account) external payable {
collateralizeInternal(account, ethAddress, msg.value);
}
/// @notice Sender approves the account to withdraw the collateral
/// @param account Address is allowed to withdraw the collateral
/// @param collateral Address of the given collateral
/// @param amount The amount is allowed to withdrawn
function approveWithdrawCollateral (address account, address collateral, uint256 amount)
external
accountIsValid(account)
collateralIsActive(collateral)
{
collaterals[msg.sender][collateral].allowance[account] = amount;
}
/// @notice Withdraw a collateral
/// @param collateral Address of the given collateral
/// @param amount The amount will be withdrawn from the collateral
function withdrawCollateral (address collateral, uint256 amount)
external
{
withdrawCollateralInternal(msg.sender, collateral, amount);
}
/// @notice Sender withdraws a collateral belonging to the user
/// @param account Address of the user
/// @param collateral Address of the given collateral
/// @param amount The amount will be withdrawn from the collateral
function withdrawCollateralBehalf (address account, address collateral, uint256 amount)
external
{
uint256 allowance = collaterals[account][collateral].allowance[msg.sender];
require(
amount <= allowance,
"Withdraw not allowed"
);
collaterals[account][collateral].allowance[msg.sender] = allowance.sub(amount);
withdrawCollateralInternal(account, collateral, amount);
}
/// @notice Sender approves the account to borrow a given market based on given collateral
/// @param account Address that is allowed to borrow the given market
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @param amount The amount is allowed to withdrawn
function approveBorrow (address account, address market, address collateral, uint256 amount)
external
accountIsValid(account)
marketIsActive(market)
{
borrows[msg.sender][collateral][market].allowance[account] = amount;
}
/// @notice Borrow an asset
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @param amount The amount of the given market will be borrowed
/// @param referralCode A unique code used as an identifier of referrer
function borrow (address market, address collateral, uint256 amount, uint16 referralCode)
external
{
borrowInternal(msg.sender, market, collateral, amount, referralCode);
}
/// @notice Sender borrows an asset belonging to the borrower
/// @param account Address of the borrower
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @param amount The amount will be borrowed
/// @param referralCode A unique code used as an identifier of referrer
function borrowBehalf (address account, address market, address collateral, uint256 amount, uint16 referralCode)
external
{
uint256 allowance = borrows[account][collateral][market].allowance[msg.sender];
require(
amount <= allowance,
"Withdraw not allowed"
);
borrows[account][collateral][market].allowance[msg.sender] = allowance.sub(amount);
borrowInternal(account, market, collateral, amount, referralCode);
}
/// @notice Repay an ERC20 asset based on a given collateral
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @param amount The amount of the market will be Repaid
function repayBorrow (address market, address collateral, uint256 amount)
external
isNotETHAddress(market)
{
repayBorrowInternal(msg.sender, market, collateral, amount);
}
/// @notice Repay an ETH based on a given collateral
/// @notice msg.value The amount of ETH will be repaid
/// @param collateral Address of the given collateral
function repayBorrow (address collateral) external payable {
repayBorrowInternal(msg.sender, ethAddress, collateral, msg.value);
}
/// @notice Sender repays an ERC20 asset based on a given collateral belonging to the borrower
/// @param account Address of the borrower
/// @param market Address of the given market
/// @param collateral Address of the given collateral
/// @param amount The amount of the market will be repaid
function repayBorrowBehalf (address account, address market, address collateral, uint256 amount)
external
isNotETHAddress(market)
{
repayBorrowInternal(account, market, collateral, amount);
}
/// @notice Sender repays an ETH based on a given collateral belonging to the borrower
/// @notice msg.value The amount of ETH sender repays belonging to the borrower
/// @param account Address of the borrower
/// @param collateral Address of the given collateral
function repayBorrowBehalf (address account, address collateral)
external
payable
{
repayBorrowInternal(account, ethAddress, collateral, msg.value);
}
/// @notice Liquidate borrower's collateral
/// @param borrower Address of the borrower who should be liquidated
/// @param market Address of the given market
/// @param collateral Address of the given collateral
function liquidateBorrowerCollateral (address borrower, address market, address collateral)
external
whenNotPaused("liquidateBorrowerCollateral")
{
MarketData memory borrowData;
(borrowData.balance, borrowData.interest,) = getAccountBorrow(borrower, market, collateral);
require(borrowData.balance > 0, "User should have debt");
(uint256 collateralBalance, uint256 timeSinceLastActivity,,, bool underCollateral) =
getAccountCollateral(borrower, collateral);
require (underCollateral || (timeSinceLastActivity > secondsPerYear),
"User should be under collateral or time is over"
);
uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest);
uint256 totalBorrowedBalanceValue = holdefiPrices.getAssetValueFromAmount(market, totalBorrowedBalance);
uint256 liquidatedCollateralValue = totalBorrowedBalanceValue
.mul(holdefiSettings.collateralAssets(collateral).penaltyRate)
.div(rateDecimals);
uint256 liquidatedCollateral =
holdefiPrices.getAssetAmountFromValue(collateral, liquidatedCollateralValue);
if (liquidatedCollateral > collateralBalance) {
liquidatedCollateral = collateralBalance;
}
collaterals[borrower][collateral].balance = collateralBalance.sub(liquidatedCollateral);
collateralAssets[collateral].totalCollateral =
collateralAssets[collateral].totalCollateral.sub(liquidatedCollateral);
collateralAssets[collateral].totalLiquidatedCollateral =
collateralAssets[collateral].totalLiquidatedCollateral.add(liquidatedCollateral);
delete borrows[borrower][collateral][market];
beforeChangeSupplyRate(market);
marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(borrowData.balance);
marketDebt[collateral][market] = marketDebt[collateral][market].add(totalBorrowedBalance);
emit CollateralLiquidated(borrower, market, collateral, totalBorrowedBalance, liquidatedCollateral);
}
/// @notice Buy collateral in exchange for ERC20 asset
/// @param market Address of the market asset should be paid to buy collateral
/// @param collateral Address of the liquidated collateral
/// @param marketAmount The amount of the given market will be paid
function buyLiquidatedCollateral (address market, address collateral, uint256 marketAmount)
external
isNotETHAddress(market)
{
buyLiquidatedCollateralInternal(market, collateral, marketAmount);
}
/// @notice Buy collateral in exchange for ETH
/// @notice msg.value The amount of the given market that will be paid
/// @param collateral Address of the liquidated collateral
function buyLiquidatedCollateral (address collateral) external payable {
buyLiquidatedCollateralInternal(ethAddress, collateral, msg.value);
}
/// @notice Deposit ERC20 asset as liquidation reserve
/// @param collateral Address of the given collateral
/// @param amount The amount that will be deposited
function depositLiquidationReserve(address collateral, uint256 amount)
external
isNotETHAddress(collateral)
{
depositLiquidationReserveInternal(collateral, amount);
}
/// @notice Deposit ETH asset as liquidation reserve
/// @notice msg.value The amount of ETH that will be deposited
function depositLiquidationReserve() external payable {
depositLiquidationReserveInternal(ethAddress, msg.value);
}
/// @notice Withdraw liquidation reserve only by the owner
/// @param collateral Address of the given collateral
/// @param amount The amount that will be withdrawn
function withdrawLiquidationReserve (address collateral, uint256 amount) external onlyOwner {
uint256 maxWithdraw = getLiquidationReserve(collateral);
uint256 transferAmount = amount;
if (transferAmount > maxWithdraw){
transferAmount = maxWithdraw;
}
collateralAssets[collateral].totalLiquidatedCollateral =
collateralAssets[collateral].totalLiquidatedCollateral.sub(transferAmount);
holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount);
emit LiquidationReserveWithdrawn(collateral, amount);
}
/// @notice Deposit ERC20 asset as promotion reserve
/// @param market Address of the given market
/// @param amount The amount that will be deposited
function depositPromotionReserve (address market, uint256 amount)
external
isNotETHAddress(market)
{
depositPromotionReserveInternal(market, amount);
}
/// @notice Deposit ETH as promotion reserve
/// @notice msg.value The amount of ETH that will be deposited
function depositPromotionReserve () external payable {
depositPromotionReserveInternal(ethAddress, msg.value);
}
/// @notice Withdraw promotion reserve only by the owner
/// @param market Address of the given market
/// @param amount The amount that will be withdrawn
function withdrawPromotionReserve (address market, uint256 amount) external onlyOwner {
(uint256 reserveScaled,) = getPromotionReserve(market);
(uint256 debtScaled,) = getPromotionDebt(market);
uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals);
uint256 increasedDebtScaled = amountScaled.add(debtScaled);
require (reserveScaled > increasedDebtScaled, "Amount should be less than max");
marketAssets[market].promotionReserveScaled = reserveScaled.sub(amountScaled);
transferFromHoldefi(msg.sender, market, amount);
emit PromotionReserveWithdrawn(market, amount);
}
/// @notice Set Holdefi prices contract only by the owner
/// @param newHoldefiPrices Address of the new Holdefi prices contract
function setHoldefiPricesContract (HoldefiPricesInterface newHoldefiPrices) external onlyOwner {
emit HoldefiPricesContractChanged(address(newHoldefiPrices), address(holdefiPrices));
holdefiPrices = newHoldefiPrices;
}
/// @notice Promotion reserve and debt settlement
/// @param market Address of the given market
function reserveSettlement (address market) external {
require(msg.sender == address(holdefiSettings), "Sender should be Holdefi Settings contract");
uint256 promotionReserve = marketAssets[market].promotionReserveScaled;
uint256 promotionDebt = marketAssets[market].promotionDebtScaled;
require(promotionReserve > promotionDebt, "Not enough promotion reserve");
promotionReserve = promotionReserve.sub(promotionDebt);
marketAssets[market].promotionReserveScaled = promotionReserve;
marketAssets[market].promotionDebtScaled = 0;
marketAssets[market].promotionReserveLastUpdateTime = block.timestamp;
marketAssets[market].promotionDebtLastUpdateTime = block.timestamp;
emit PromotionReserveUpdated(market, promotionReserve);
emit PromotionDebtUpdated(market, 0);
}
/// @notice Update supply index of a market
/// @param market Address of the given market
function updateSupplyIndex (address market) internal {
(uint256 currentSupplyIndex, uint256 supplyRate, uint256 currentTime) =
getCurrentSupplyIndex(market);
marketAssets[market].supplyIndex = currentSupplyIndex;
marketAssets[market].supplyIndexUpdateTime = currentTime;
emit UpdateSupplyIndex(market, currentSupplyIndex, supplyRate);
}
/// @notice Update borrow index of a market
/// @param market Address of the given market
function updateBorrowIndex (address market) internal {
(uint256 currentBorrowIndex,, uint256 currentTime) = getCurrentBorrowIndex(market);
marketAssets[market].borrowIndex = currentBorrowIndex;
marketAssets[market].borrowIndexUpdateTime = currentTime;
emit UpdateBorrowIndex(market, currentBorrowIndex);
}
/// @notice Update promotion reserve of a market
/// @param market Address of the given market
function updatePromotionReserve(address market) internal {
(uint256 reserveScaled,) = getPromotionReserve(market);
marketAssets[market].promotionReserveScaled = reserveScaled;
marketAssets[market].promotionReserveLastUpdateTime = block.timestamp;
emit PromotionReserveUpdated(market, reserveScaled);
}
/// @notice Update promotion debt of a market
/// @dev Promotion rate will be set to 0 if (promotionDebt >= promotionReserve)
/// @param market Address of the given market
function updatePromotionDebt(address market) internal {
(uint256 debtScaled,) = getPromotionDebt(market);
if (marketAssets[market].promotionDebtScaled != debtScaled){
marketAssets[market].promotionDebtScaled = debtScaled;
marketAssets[market].promotionDebtLastUpdateTime = block.timestamp;
emit PromotionDebtUpdated(market, debtScaled);
}
if (marketAssets[market].promotionReserveScaled <= debtScaled) {
holdefiSettings.resetPromotionRate(market);
}
}
/// @notice transfer ETH or ERC20 asset from this contract
function transferFromHoldefi(address receiver, address asset, uint256 amount) internal {
bool success = false;
if (asset == ethAddress){
(success, ) = receiver.call{value:amount}("");
}
else {
IERC20 token = IERC20(asset);
success = token.transfer(receiver, amount);
}
require (success, "Cannot Transfer");
}
/// @notice transfer ERC20 asset to this contract
function transferToHoldefi(address receiver, address asset, uint256 amount) internal {
IERC20 token = IERC20(asset);
bool success = token.transferFrom(msg.sender, receiver, amount);
require (success, "Cannot Transfer");
}
/// @notice Perform supply operation
function supplyInternal(address account, address market, uint256 amount, uint16 referralCode)
internal
whenNotPaused("supply")
marketIsActive(market)
{
if (market != ethAddress) {
transferToHoldefi(address(this), market, amount);
}
MarketData memory supplyData;
(supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market);
supplyData.balance = supplyData.balance.add(amount);
supplies[account][market].balance = supplyData.balance;
supplies[account][market].accumulatedInterest = supplyData.interest;
supplies[account][market].lastInterestIndex = supplyData.currentIndex;
beforeChangeSupplyRate(market);
marketAssets[market].totalSupply = marketAssets[market].totalSupply.add(amount);
emit Supply(
msg.sender,
account,
market,
amount,
supplyData.balance,
supplyData.interest,
supplyData.currentIndex,
referralCode
);
}
/// @notice Perform withdraw supply operation
function withdrawSupplyInternal (address account, address market, uint256 amount)
internal
whenNotPaused("withdrawSupply")
{
MarketData memory supplyData;
(supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market);
uint256 totalSuppliedBalance = supplyData.balance.add(supplyData.interest);
require (totalSuppliedBalance != 0, "Total balance should not be zero");
uint256 transferAmount = amount;
if (transferAmount > totalSuppliedBalance){
transferAmount = totalSuppliedBalance;
}
uint256 remaining = 0;
if (transferAmount <= supplyData.interest) {
supplyData.interest = supplyData.interest.sub(transferAmount);
}
else {
remaining = transferAmount.sub(supplyData.interest);
supplyData.interest = 0;
supplyData.balance = supplyData.balance.sub(remaining);
}
supplies[account][market].balance = supplyData.balance;
supplies[account][market].accumulatedInterest = supplyData.interest;
supplies[account][market].lastInterestIndex = supplyData.currentIndex;
beforeChangeSupplyRate(market);
marketAssets[market].totalSupply = marketAssets[market].totalSupply.sub(remaining);
transferFromHoldefi(msg.sender, market, transferAmount);
emit WithdrawSupply(
msg.sender,
account,
market,
transferAmount,
supplyData.balance,
supplyData.interest,
supplyData.currentIndex
);
}
/// @notice Perform collateralize operation
function collateralizeInternal (address account, address collateral, uint256 amount)
internal
whenNotPaused("collateralize")
collateralIsActive(collateral)
{
if (collateral != ethAddress) {
transferToHoldefi(address(holdefiCollaterals), collateral, amount);
}
else {
transferFromHoldefi(address(holdefiCollaterals), collateral, amount);
}
uint256 balance = collaterals[account][collateral].balance.add(amount);
collaterals[account][collateral].balance = balance;
collaterals[account][collateral].lastUpdateTime = block.timestamp;
collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.add(amount);
emit Collateralize(msg.sender, account, collateral, amount, balance);
}
/// @notice Perform withdraw collateral operation
function withdrawCollateralInternal (address account, address collateral, uint256 amount)
internal
whenNotPaused("withdrawCollateral")
{
(uint256 balance,, uint256 borrowPowerValue, uint256 totalBorrowValue,) =
getAccountCollateral(account, collateral);
require (borrowPowerValue != 0, "Borrow power should not be zero");
uint256 collateralNedeed = 0;
if (totalBorrowValue != 0) {
uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate;
uint256 totalCollateralValue = totalBorrowValue.mul(valueToLoanRate).div(rateDecimals);
collateralNedeed = holdefiPrices.getAssetAmountFromValue(collateral, totalCollateralValue);
}
uint256 maxWithdraw = balance.sub(collateralNedeed);
uint256 transferAmount = amount;
if (transferAmount > maxWithdraw){
transferAmount = maxWithdraw;
}
balance = balance.sub(transferAmount);
collaterals[account][collateral].balance = balance;
collaterals[account][collateral].lastUpdateTime = block.timestamp;
collateralAssets[collateral].totalCollateral =
collateralAssets[collateral].totalCollateral.sub(transferAmount);
holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount);
emit WithdrawCollateral(msg.sender, account, collateral, transferAmount, balance);
}
/// @notice Perform borrow operation
function borrowInternal (address account, address market, address collateral, uint256 amount, uint16 referralCode)
internal
whenNotPaused("borrow")
marketIsActive(market)
collateralIsActive(collateral)
{
require (
amount <= (marketAssets[market].totalSupply.sub(marketAssets[market].totalBorrow)),
"Amount should be less than cash"
);
(,, uint256 borrowPowerValue,,) = getAccountCollateral(account, collateral);
uint256 assetToBorrowValue = holdefiPrices.getAssetValueFromAmount(market, amount);
require (
borrowPowerValue >= assetToBorrowValue,
"Borrow power should be more than new borrow value"
);
MarketData memory borrowData;
(borrowData.balance, borrowData.interest, borrowData.currentIndex) = getAccountBorrow(account, market, collateral);
borrowData.balance = borrowData.balance.add(amount);
borrows[account][collateral][market].balance = borrowData.balance;
borrows[account][collateral][market].accumulatedInterest = borrowData.interest;
borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex;
collaterals[account][collateral].lastUpdateTime = block.timestamp;
beforeChangeSupplyRate(market);
marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.add(amount);
transferFromHoldefi(msg.sender, market, amount);
emit Borrow(
msg.sender,
account,
market,
collateral,
amount,
borrowData.balance,
borrowData.interest,
borrowData.currentIndex,
referralCode
);
}
/// @notice Perform repay borrow operation
function repayBorrowInternal (address account, address market, address collateral, uint256 amount)
internal
whenNotPaused("repayBorrow")
{
MarketData memory borrowData;
(borrowData.balance, borrowData.interest, borrowData.currentIndex) =
getAccountBorrow(account, market, collateral);
uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest);
require (totalBorrowedBalance != 0, "Total balance should not be zero");
uint256 transferAmount = amount;
if (transferAmount > totalBorrowedBalance) {
transferAmount = totalBorrowedBalance;
if (market == ethAddress) {
uint256 extra = amount.sub(transferAmount);
transferFromHoldefi(msg.sender, ethAddress, extra);
}
}
if (market != ethAddress) {
transferToHoldefi(address(this), market, transferAmount);
}
uint256 remaining = 0;
if (transferAmount <= borrowData.interest) {
borrowData.interest = borrowData.interest.sub(transferAmount);
}
else {
remaining = transferAmount.sub(borrowData.interest);
borrowData.interest = 0;
borrowData.balance = borrowData.balance.sub(remaining);
}
borrows[account][collateral][market].balance = borrowData.balance;
borrows[account][collateral][market].accumulatedInterest = borrowData.interest;
borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex;
collaterals[account][collateral].lastUpdateTime = block.timestamp;
beforeChangeSupplyRate(market);
marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(remaining);
emit RepayBorrow (
msg.sender,
account,
market,
collateral,
transferAmount,
borrowData.balance,
borrowData.interest,
borrowData.currentIndex
);
}
/// @notice Perform buy liquidated collateral operation
function buyLiquidatedCollateralInternal (address market, address collateral, uint256 marketAmount)
internal
whenNotPaused("buyLiquidatedCollateral")
{
uint256 debt = marketDebt[collateral][market];
require (marketAmount <= debt,
"Amount should be less than total liquidated assets"
);
uint256 collateralAmountWithDiscount =
getDiscountedCollateralAmount(market, collateral, marketAmount);
uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral;
require (
collateralAmountWithDiscount <= totalLiquidatedCollateral,
"Collateral amount with discount should be less than total liquidated assets"
);
if (market != ethAddress) {
transferToHoldefi(address(this), market, marketAmount);
}
collateralAssets[collateral].totalLiquidatedCollateral = totalLiquidatedCollateral.sub(collateralAmountWithDiscount);
marketDebt[collateral][market] = debt.sub(marketAmount);
holdefiCollaterals.withdraw(collateral, msg.sender, collateralAmountWithDiscount);
emit BuyLiquidatedCollateral(market, collateral, marketAmount, collateralAmountWithDiscount);
}
/// @notice Perform deposit promotion reserve operation
function depositPromotionReserveInternal (address market, uint256 amount)
internal
marketIsActive(market)
{
if (market != ethAddress) {
transferToHoldefi(address(this), market, amount);
}
uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals);
marketAssets[market].promotionReserveScaled =
marketAssets[market].promotionReserveScaled.add(amountScaled);
emit PromotionReserveDeposited(market, amount);
}
/// @notice Perform deposit liquidation reserve operation
function depositLiquidationReserveInternal (address collateral, uint256 amount)
internal
collateralIsActive(ethAddress)
{
if (collateral != ethAddress) {
transferToHoldefi(address(holdefiCollaterals), collateral, amount);
}
else {
transferFromHoldefi(address(holdefiCollaterals), collateral, amount);
}
collateralAssets[ethAddress].totalLiquidatedCollateral =
collateralAssets[ethAddress].totalLiquidatedCollateral.add(msg.value);
emit LiquidationReserveDeposited(ethAddress, msg.value);
}
} | @notice Returns balance and interest of an account for a given market @dev supplyInterest = accumulatedInterest + (balance * (marketSupplyIndex - userLastSupplyInterestIndex)) @param account Supplier address to get supply information @param market Address of the given market @return balance Supplied amount on the specified market @return interest Profit earned @return currentSupplyIndex Supply index for the given market at current time | function getAccountSupply(address account, address market)
public
view
returns (uint256 balance, uint256 interest, uint256 currentSupplyIndex)
{
balance = supplies[account][market].balance;
(currentSupplyIndex,,) = getCurrentSupplyIndex(market);
uint256 deltaInterestIndex = currentSupplyIndex.sub(supplies[account][market].lastInterestIndex);
uint256 deltaInterestScaled = deltaInterestIndex.mul(balance);
uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals);
interest = supplies[account][market].accumulatedInterest.add(deltaInterest);
}
| 13,514,315 | [
1,
1356,
11013,
471,
16513,
434,
392,
2236,
364,
279,
864,
13667,
225,
14467,
29281,
273,
24893,
29281,
397,
261,
12296,
225,
261,
27151,
3088,
1283,
1016,
300,
729,
3024,
3088,
1283,
29281,
1016,
3719,
225,
2236,
17216,
1758,
358,
336,
14467,
1779,
225,
13667,
5267,
434,
326,
864,
13667,
327,
11013,
3425,
3110,
3844,
603,
326,
1269,
13667,
327,
16513,
1186,
7216,
425,
1303,
329,
327,
783,
3088,
1283,
1016,
3425,
1283,
770,
364,
326,
864,
13667,
622,
783,
813,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
23393,
3088,
1283,
12,
2867,
2236,
16,
1758,
13667,
13,
203,
202,
202,
482,
203,
202,
202,
1945,
203,
202,
202,
6154,
261,
11890,
5034,
11013,
16,
2254,
5034,
16513,
16,
2254,
5034,
783,
3088,
1283,
1016,
13,
203,
202,
95,
203,
202,
202,
12296,
273,
1169,
5259,
63,
4631,
6362,
27151,
8009,
12296,
31,
203,
203,
202,
202,
12,
2972,
3088,
1283,
1016,
16408,
13,
273,
5175,
3088,
1283,
1016,
12,
27151,
1769,
203,
203,
202,
202,
11890,
5034,
3622,
29281,
1016,
273,
783,
3088,
1283,
1016,
18,
1717,
12,
2859,
5259,
63,
4631,
6362,
27151,
8009,
2722,
29281,
1016,
1769,
203,
202,
202,
11890,
5034,
3622,
29281,
55,
12825,
273,
3622,
29281,
1016,
18,
16411,
12,
12296,
1769,
203,
202,
202,
11890,
5034,
3622,
29281,
273,
3622,
29281,
55,
12825,
18,
2892,
12,
7572,
2173,
5593,
2934,
2892,
12,
5141,
31809,
1769,
203,
1082,
203,
202,
202,
2761,
395,
273,
1169,
5259,
63,
4631,
6362,
27151,
8009,
8981,
5283,
690,
29281,
18,
1289,
12,
9878,
29281,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/421613/0x1474236fEB9E96Cf0B9f913fF5418856139caAe3/sources/contracts/Game.sol | @notice Setter to set the allocation of a specific protocol by a basketId. Only the owner of the basket can set this. @param _basketId Basket ID (tokenID) in the BasketToken (NFT) contract. @param _chainId number of chainId. @param _protocolId Id of the protocol of which the allocation is queried. @param _allocation Number of derby tokens that are allocated towards this specific protocol. | function setBasketAllocationInProtocol(
uint256 _basketId,
uint256 _chainId,
uint256 _protocolId,
int256 _allocation
) internal onlyBasketOwner(_basketId) {
baskets[_basketId].allocations[_chainId][_protocolId] += _allocation;
require(basketAllocationInProtocol(_basketId, _chainId, _protocolId) >= 0, "Basket: underflow");
}
| 11,576,150 | [
1,
8465,
358,
444,
326,
13481,
434,
279,
2923,
1771,
635,
279,
12886,
548,
18,
5098,
326,
3410,
434,
326,
12886,
848,
444,
333,
18,
225,
389,
26219,
548,
605,
7064,
1599,
261,
2316,
734,
13,
316,
326,
605,
7064,
1345,
261,
50,
4464,
13,
6835,
18,
225,
389,
5639,
548,
1300,
434,
2687,
548,
18,
225,
389,
8373,
548,
3124,
434,
326,
1771,
434,
1492,
326,
13481,
353,
23264,
18,
225,
389,
29299,
3588,
434,
4854,
1637,
2430,
716,
854,
11977,
23248,
333,
2923,
1771,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
444,
11324,
17353,
382,
5752,
12,
203,
565,
2254,
5034,
389,
26219,
548,
16,
203,
565,
2254,
5034,
389,
5639,
548,
16,
203,
565,
2254,
5034,
389,
8373,
548,
16,
203,
565,
509,
5034,
389,
29299,
203,
225,
262,
2713,
1338,
11324,
5541,
24899,
26219,
548,
13,
288,
203,
565,
324,
835,
2413,
63,
67,
26219,
548,
8009,
9853,
1012,
63,
67,
5639,
548,
6362,
67,
8373,
548,
65,
1011,
389,
29299,
31,
203,
565,
2583,
12,
26219,
17353,
382,
5752,
24899,
26219,
548,
16,
389,
5639,
548,
16,
389,
8373,
548,
13,
1545,
374,
16,
315,
11324,
30,
3613,
2426,
8863,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//TheEthadams's Prod Ready.
//https://rinkeby.etherscan.io/address/0x8d4665fe98968707da5042be347060e673da98f1#code
pragma solidity ^0.4.22;
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract TokenERC20 {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals
uint256 public totalSupply = 500000000 * 10 ** uint256(decimals);
//Address founder
address public owner;
//Address Development.
address public development = 0x23556CF8E8997f723d48Ab113DAbed619E7a9786;
//Start timestamp
//End timestamp
uint public startTime;
uint public icoDays;
uint public stopTime;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
string tokenName,
string tokenSymbol
) public {
totalSupply = totalSupply; // Update total supply.
balanceOf[msg.sender] = 150000000 * 10 ** uint256(decimals);
//Give this contract some token balances.
balanceOf[this] = 350000000 * 10 ** uint256(decimals);
//Set the name for display purposes
name = tokenName;
//Set the symbol for display purposes
symbol = tokenSymbol;
//Assign owner.
owner = msg.sender;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
modifier onlyDeveloper() {
require(msg.sender == development);
_;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
require(now >= stopTime);//Transfer only after ICO.
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
if(now < stopTime){
require(_from == owner);//Only owner can move the tokens before ICO is over.
_transfer(_from, _to, _value);
} else {
_transfer(_from, _to, _value);
}
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/******************************************/
/* ADVANCED TOKEN STARTS HERE */
/******************************************/
contract OffGridParadise is TokenERC20 {
uint256 public buyPrice;
bool private isKilled; //Changed to true if the contract is killed.
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor (
string tokenName,
string tokenSymbol
) TokenERC20(tokenName, tokenSymbol) public {
//Initializes the timestamps
startTime = now;
isKilled = false;
//This is the PRE-ICO price.Assuming the price of ethereum is $600per Ether.
setPrice(13300);
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address(Number greater than Zero).
require (balanceOf[_from] >= _value); // Check if the sender has enough //Use burn() instead
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
emit Transfer(_from, _to, _value);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyDeveloper public {
require(target != development);
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
//Buy tokens from the contract by sending ethers.
function buyTokens () payable public {
require(isKilled == false);
require(msg.sender != development);
require(msg.sender != owner);
uint amount = msg.value * buyPrice;
owner.transfer(msg.value);
_transfer(this, msg.sender, amount);
}
//Buy tokens from the contract by sending ethers(Fall Back Function).
function () payable public {
require(isKilled == false);
require(msg.sender != development);
require(msg.sender != owner);
uint amount = msg.value * buyPrice;
owner.transfer(msg.value);
if(balanceOf[this] > amount){
_transfer(this, msg.sender, amount);
} else {
_transfer(owner,msg.sender,amount);
}
}
function setPrice(uint256 newBuyingPrice) onlyOwner public {
buyPrice = newBuyingPrice;
}
function setStopTime(uint icodays) onlyOwner public {
//Minutes in a day is 1440
icoDays = icodays * 1 days;//Production Purposes.
stopTime = startTime + icoDays;
}
//Transfer transferOwnership
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
//Stop the contract.
function killContract() onlyOwner public {
isKilled = true;
}
} | This generates a public event on the blockchain that will notify clients */ Initializes contract with initial supply tokens to the creator of the contract */Initializes the timestampsThis is the PRE-ICO price.Assuming the price of ethereum is $600per Ether. | ) TokenERC20(tokenName, tokenSymbol) public {
startTime = now;
isKilled = false;
setPrice(13300);
}
| 2,127,457 | [
1,
2503,
6026,
279,
1071,
871,
603,
326,
16766,
716,
903,
5066,
7712,
342,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
342,
9685,
326,
11267,
2503,
353,
326,
7071,
17,
2871,
51,
6205,
18,
2610,
21249,
326,
6205,
434,
13750,
822,
379,
353,
271,
28133,
457,
512,
1136,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
262,
3155,
654,
39,
3462,
12,
2316,
461,
16,
1147,
5335,
13,
1071,
288,
203,
1377,
8657,
273,
2037,
31,
203,
1377,
353,
47,
13148,
225,
273,
629,
31,
203,
1377,
444,
5147,
12,
3437,
19249,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xA6B816010Ab51e088C4F19c71ABa87E54b422E14/sources/basedAIFarm.sol | Accumulated basedAI per share, times 1e18. | uint256 public accbasedAIPerShareMultiple = 1e18;
| 4,185,184 | [
1,
8973,
5283,
690,
2511,
18194,
1534,
7433,
16,
4124,
404,
73,
2643,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
4078,
12261,
18194,
2173,
9535,
8438,
273,
404,
73,
2643,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x441761326490cACF7aF299725B6292597EE822c2/sources/UNFI.sol | * @dev Gets the last token transaction of the specified address. @param owner The address to query the balance of./ | function lastTransactionOf(address owner) public view returns (uint256,uint256) {
return (_lastSendTransaction[owner],_lastReceiveTransaction[owner]);
}
| 2,615,348 | [
1,
3002,
326,
1142,
1147,
2492,
225,
434,
326,
1269,
1758,
18,
225,
3410,
1021,
1758,
358,
843,
326,
11013,
434,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1142,
3342,
951,
12,
2867,
3410,
13,
1071,
1476,
1135,
261,
11890,
5034,
16,
11890,
5034,
13,
288,
203,
3639,
327,
261,
67,
2722,
3826,
3342,
63,
8443,
6487,
67,
2722,
11323,
3342,
63,
8443,
19226,
203,
565,
289,
377,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0xE956528C7E9aa2390aC8995e9489E2CCde449F19/sources/contracts/CurveSampler.sol | Break early if there are 0 amounts | {
uint256 numSamples = takerTokenAmounts.length;
makerTokenAmounts = new uint256[](numSamples);
for (uint256 i = 0; i < numSamples; i++) {
uint256 buyAmount;
if(noLending) {
buyAmount = ICurve(curveAddress).get_dy(fromTokenIdx, toTokenIdx, takerTokenAmounts[i]);
buyAmount = ICurve(curveAddress).get_dy_underlying(fromTokenIdx, toTokenIdx, takerTokenAmounts[i]);
}
makerTokenAmounts[i] = buyAmount;
if (makerTokenAmounts[i] == 0) {
break;
}
}
return makerTokenAmounts;
}
| 4,674,501 | [
1,
7634,
11646,
309,
1915,
854,
374,
30980,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
2254,
5034,
818,
13239,
273,
268,
6388,
1345,
6275,
87,
18,
2469,
31,
203,
3639,
312,
6388,
1345,
6275,
87,
273,
394,
2254,
5034,
8526,
12,
2107,
13239,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
818,
13239,
31,
277,
27245,
288,
203,
5411,
2254,
5034,
30143,
6275,
31,
203,
5411,
309,
12,
2135,
48,
2846,
13,
288,
203,
7734,
30143,
6275,
273,
467,
9423,
12,
16683,
1887,
2934,
588,
67,
15680,
12,
2080,
1345,
4223,
16,
358,
1345,
4223,
16,
268,
6388,
1345,
6275,
87,
63,
77,
19226,
203,
7734,
30143,
6275,
273,
467,
9423,
12,
16683,
1887,
2934,
588,
67,
15680,
67,
9341,
6291,
12,
2080,
1345,
4223,
16,
358,
1345,
4223,
16,
268,
6388,
1345,
6275,
87,
63,
77,
19226,
203,
5411,
289,
203,
9079,
203,
5411,
312,
6388,
1345,
6275,
87,
63,
77,
65,
273,
30143,
6275,
31,
203,
5411,
309,
261,
29261,
1345,
6275,
87,
63,
77,
65,
422,
374,
13,
288,
203,
7734,
898,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
312,
6388,
1345,
6275,
87,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
// Context abstract contract implements some context tooling functions.
contract Context {
// _sender returns the address of the current trx sender
function _sender() internal view returns (address) {
return msg.sender;
}
// _now returns the current timestamp as available to the contract call
function _now() internal view returns (uint256) {
return block.timestamp;
}
}
| Context abstract contract implements some context tooling functions. _sender returns the address of the current trx sender | contract Context {
pragma solidity ^0.6.0;
function _sender() internal view returns (address) {
return msg.sender;
}
function _now() internal view returns (uint256) {
return block.timestamp;
}
}
| 1,833,817 | [
1,
1042,
8770,
6835,
4792,
2690,
819,
5226,
310,
4186,
18,
389,
15330,
1135,
326,
1758,
434,
326,
783,
433,
92,
5793,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1772,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
20,
31,
203,
565,
445,
389,
15330,
1435,
2713,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
389,
3338,
1435,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
1203,
18,
5508,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.10;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*///////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*///////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*///////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*///////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
/*///////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool callStatus;
assembly {
// Transfer the ETH and store if it succeeded or not.
callStatus := call(gas(), to, amount, 0, 0, 0, 0)
}
require(callStatus, "ETH_TRANSFER_FAILED");
}
/*///////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.
mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument.
mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 100 because the calldata length is 4 + 32 * 3.
callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 68 because the calldata length is 4 + 32 * 2.
callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector.
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 68 because the calldata length is 4 + 32 * 2.
callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED");
}
/*///////////////////////////////////////////////////////////////
INTERNAL HELPER LOGIC
//////////////////////////////////////////////////////////////*/
function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) {
assembly {
// Get how many bytes the call returned.
let returnDataSize := returndatasize()
// If the call reverted:
if iszero(callStatus) {
// Copy the revert message into memory.
returndatacopy(0, 0, returnDataSize)
// Revert with the same message.
revert(0, returnDataSize)
}
switch returnDataSize
case 32 {
// Copy the return data into memory.
returndatacopy(0, 0, returnDataSize)
// Set success to whether it returned true.
success := iszero(iszero(mload(0)))
}
case 0 {
// There was no return data.
success := 1
}
default {
// It returned some malformed output.
success := 0
}
}
}
}
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
/*///////////////////////////////////////////////////////////////
SIMPLIFIED FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
}
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
}
function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
}
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
}
/*///////////////////////////////////////////////////////////////
LOW LEVEL FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function mulDivDown(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// Divide z by the denominator.
z := div(z, denominator)
}
}
function mulDivUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// First, divide z - 1 by the denominator and add 1.
// We allow z - 1 to underflow if z is 0, because we multiply the
// end result by 0 if z is zero, ensuring we return 0 if z is zero.
z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
}
}
function rpow(
uint256 x,
uint256 n,
uint256 scalar
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := scalar
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store scalar in z for now.
z := scalar
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, scalar)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, scalar)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, scalar)
}
}
}
}
}
/*///////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
assembly {
// Start off with z at 1.
z := 1
// Used below to help find a nearby power of 2.
let y := x
// Find the lowest power of 2 that is at least sqrt(x).
if iszero(lt(y, 0x100000000000000000000000000000000)) {
y := shr(128, y) // Like dividing by 2 ** 128.
z := shl(64, z)
}
if iszero(lt(y, 0x10000000000000000)) {
y := shr(64, y) // Like dividing by 2 ** 64.
z := shl(32, z)
}
if iszero(lt(y, 0x100000000)) {
y := shr(32, y) // Like dividing by 2 ** 32.
z := shl(16, z)
}
if iszero(lt(y, 0x10000)) {
y := shr(16, y) // Like dividing by 2 ** 16.
z := shl(8, z)
}
if iszero(lt(y, 0x100)) {
y := shr(8, y) // Like dividing by 2 ** 8.
z := shl(4, z)
}
if iszero(lt(y, 0x10)) {
y := shr(4, y) // Like dividing by 2 ** 4.
z := shl(2, z)
}
if iszero(lt(y, 0x8)) {
// Equivalent to 2 ** z.
z := shl(1, z)
}
// Shifting right by 1 is like dividing by 2.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// Compute a rounded down version of z.
let zRoundDown := div(x, z)
// If zRoundDown is smaller, use it.
if lt(zRoundDown, z) {
z := zRoundDown
}
}
}
}
/// @notice Minimal ERC4646 tokenized Vault implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/mixins/ERC4626.sol)
/// @dev Do not use in production! ERC-4626 is still in the review stage and is subject to change.
abstract contract ERC4626 is ERC20 {
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Deposit(address indexed from, address indexed to, uint256 amount, uint256 shares);
event Withdraw(address indexed from, address indexed to, uint256 amount, uint256 shares);
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
ERC20 public immutable asset;
uint256 internal immutable ONE;
constructor(
ERC20 _asset,
string memory _name,
string memory _symbol
) ERC20(_name, _symbol, _asset.decimals()) {
asset = _asset;
unchecked {
ONE = 10**decimals; // >77 decimals is unlikely.
}
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LOGIC
//////////////////////////////////////////////////////////////*/
function deposit(uint256 amount, address to) public virtual returns (uint256 shares) {
// Check for rounding error since we round down in previewDeposit.
require((shares = previewDeposit(amount)) != 0, "ZERO_SHARES");
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), amount);
_mint(to, shares);
emit Deposit(msg.sender, to, amount, shares);
afterDeposit(amount, shares);
}
function mint(uint256 shares, address to) public virtual returns (uint256 amount) {
amount = previewMint(shares); // No need to check for rounding error, previewMint rounds up.
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), amount);
_mint(to, shares);
emit Deposit(msg.sender, to, amount, shares);
afterDeposit(amount, shares);
}
function withdraw(
uint256 amount,
address to,
address from
) public virtual returns (uint256 shares) {
shares = previewWithdraw(amount); // No need to check for rounding error, previewWithdraw rounds up.
if (msg.sender != from) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - shares;
}
beforeWithdraw(amount, shares);
_burn(from, shares);
emit Withdraw(from, to, amount, shares);
asset.safeTransfer(to, amount);
}
function redeem(
uint256 shares,
address to,
address from
) public virtual returns (uint256 amount) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (msg.sender != from && allowed != type(uint256).max) allowance[from][msg.sender] = allowed - shares;
// Check for rounding error since we round down in previewRedeem.
require((amount = previewRedeem(shares)) != 0, "ZERO_ASSETS");
beforeWithdraw(amount, shares);
_burn(from, shares);
emit Withdraw(from, to, amount, shares);
asset.safeTransfer(to, amount);
}
/*///////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
function totalAssets() public view virtual returns (uint256);
function assetsOf(address user) public view virtual returns (uint256) {
return previewRedeem(balanceOf[user]);
}
function assetsPerShare() public view virtual returns (uint256) {
return previewRedeem(ONE);
}
function previewDeposit(uint256 amount) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? amount : amount.mulDivDown(supply, totalAssets());
}
function previewMint(uint256 shares) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);
}
function previewWithdraw(uint256 amount) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? amount : amount.mulDivUp(supply, totalAssets());
}
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LIMIT LOGIC
//////////////////////////////////////////////////////////////*/
function maxDeposit(address) public virtual returns (uint256) {
return type(uint256).max;
}
function maxMint(address) public virtual returns (uint256) {
return type(uint256).max;
}
function maxWithdraw(address user) public virtual returns (uint256) {
return assetsOf(user);
}
function maxRedeem(address user) public virtual returns (uint256) {
return balanceOf[user];
}
/*///////////////////////////////////////////////////////////////
INTERNAL HOOKS LOGIC
//////////////////////////////////////////////////////////////*/
function beforeWithdraw(uint256 amount, uint256 shares) internal virtual {}
function afterDeposit(uint256 amount, uint256 shares) internal virtual {}
}
/// @title Rewards Claiming Contract
/// @author joeysantoro
contract RewardsClaimer {
using SafeTransferLib for ERC20;
event RewardDestinationUpdate(address indexed newDestination);
event ClaimRewards(address indexed rewardToken, uint256 amount);
/// @notice the address to send rewards
address public rewardDestination;
/// @notice the array of reward tokens to send to
ERC20[] public rewardTokens;
constructor(
address _rewardDestination,
ERC20[] memory _rewardTokens
) {
rewardDestination = _rewardDestination;
rewardTokens = _rewardTokens;
}
/// @notice claim all token rewards
function claimRewards() public {
beforeClaim(); // hook to accrue/pull in rewards, if needed
uint256 len = rewardTokens.length;
// send all tokens to destination
for (uint256 i = 0; i < len; i++) {
ERC20 token = rewardTokens[i];
uint256 amount = token.balanceOf(address(this));
token.safeTransfer(rewardDestination, amount);
emit ClaimRewards(address(token), amount);
}
}
/// @notice set the address of the new reward destination
/// @param newDestination the new reward destination
function setRewardDestination(address newDestination) external {
require(msg.sender == rewardDestination, "UNAUTHORIZED");
rewardDestination = newDestination;
emit RewardDestinationUpdate(newDestination);
}
/// @notice hook to accrue/pull in rewards, if needed
function beforeClaim() internal virtual {}
}
// Docs: https://docs.convexfinance.com/convexfinanceintegration/booster
// main Convex contract(booster.sol) basic interface
interface IConvexBooster {
// deposit into convex, receive a tokenized deposit. parameter to stake immediately
function deposit(uint256 _pid, uint256 _amount, bool _stake) external returns(bool);
}
interface IConvexBaseRewardPool {
function pid() external view returns (uint256);
function withdrawAndUnwrap(uint256 amount, bool claim) external returns(bool);
function getReward(address _account, bool _claimExtras) external returns(bool);
function balanceOf(address account) external view returns (uint256);
function extraRewards(uint256 index) external view returns(IRewards);
function extraRewardsLength() external view returns(uint);
function rewardToken() external view returns(ERC20);
}
interface IRewards {
function rewardToken() external view returns(ERC20);
}
/// @title Convex Finance Yield Bearing Vault
/// @author joeysantoro
contract ConvexERC4626 is ERC4626, RewardsClaimer {
using SafeTransferLib for ERC20;
/// @notice The Convex Booster contract (for deposit/withdraw)
IConvexBooster public immutable convexBooster;
/// @notice The Convex Rewards contract (for claiming rewards)
IConvexBaseRewardPool public immutable convexRewards;
uint256 public immutable pid;
/**
@notice Creates a new Vault that accepts a specific underlying token.
@param _asset The ERC20 compliant token the Vault should accept.
@param _name The name for the vault token.
@param _symbol The symbol for the vault token.
@param _convexBooster The Convex Booster contract (for deposit/withdraw).
@param _convexRewards The Convex Rewards contract (for claiming rewards).
@param _rewardsDestination the address to send CRV and CVX.
@param _rewardTokens the rewards tokens to send out.
*/
constructor(
ERC20 _asset,
string memory _name,
string memory _symbol,
IConvexBooster _convexBooster,
IConvexBaseRewardPool _convexRewards,
address _rewardsDestination,
ERC20[] memory _rewardTokens
)
ERC4626(_asset, _name, _symbol)
RewardsClaimer(_rewardsDestination, _rewardTokens)
{
convexBooster = _convexBooster;
convexRewards = _convexRewards;
pid = _convexRewards.pid();
_asset.approve(address(_convexBooster), type(uint256).max);
}
function updateRewardTokens() public {
uint256 len = convexRewards.extraRewardsLength();
require(len < 5, "exceed max rewards");
delete rewardTokens;
for (uint256 i = 0; i < len; i++) {
rewardTokens.push(convexRewards.extraRewards(i).rewardToken());
}
rewardTokens.push(convexRewards.rewardToken());
}
function afterDeposit(uint256 amount, uint256) internal override {
require(convexBooster.deposit(pid, amount, true), "deposit error");
}
function beforeWithdraw(uint256 amount, uint256) internal override {
require(convexRewards.withdrawAndUnwrap(amount, false), "withdraw error");
}
function beforeClaim() internal override {
require(convexRewards.getReward(address(this), true), "rewards error");
}
/// @notice Calculates the total amount of underlying tokens the Vault holds.
/// @return The total amount of underlying tokens the Vault holds.
function totalAssets() public view override returns (uint256) {
return convexRewards.balanceOf(address(this));
}
} | Equivalent to (x * WAD) / y rounded down.
| return mulDivDown(x, WAD, y); | 41,340 | [
1,
22606,
358,
261,
92,
225,
678,
1880,
13,
342,
677,
16729,
2588,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
327,
14064,
7244,
4164,
12,
92,
16,
678,
1880,
16,
677,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// -----------------------------------------------------------------------------
// File RUS_SA_COMPARATIVE_ADV.SOL
//
// (c) Koziev Elijah
//
// Content:
// Синтаксический анализатор: связь сравнительных наречий с глаголами
//
// Подробнее о правилах: http://www.solarix.ru/for_developers/docs/rules.shtml
// -----------------------------------------------------------------------------
//
// CD->14.09.2008
// LC->11.08.2009
// --------------
#include "aa_rules.inc"
#pragma floating off
automat aa
{
operator Comparative2Verb_1 : LINK_COMPARATIVE_ADV_2_VERB
{
// 'бегает быстрее, ЧЕМ СОБАКА'
if context {
@or(НАРЕЧИЕ:*{ /*СТЕПЕНЬ:СРАВН*/ },ПРИЛАГАТЕЛЬНОЕ:*{СТЕПЕНЬ:СРАВН})
_Запятая
СОЮЗ:ЧЕМ{}
СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ }
}
then
context { 0 .<ATTRIBUTE_EXC> 3 }
}
operator Comparative2Verb_2 : LINK_COMPARATIVE_ADV_2_VERB
{
// 'бегает быстрее, ЧЕМ одна СОБАКА'
if context {
@or(НАРЕЧИЕ:*{ /*СТЕПЕНЬ:СРАВН*/ },ПРИЛАГАТЕЛЬНОЕ:*{СТЕПЕНЬ:СРАВН})
_Запятая
СОЮЗ:ЧЕМ{}
ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ }
}
then
context { 0 .<ATTRIBUTE_EXC> 3 }
}
operator Comparative2Verb_3 : LINK_COMPARATIVE_ADV_2_VERB
{
// 'бегает быстрее, ЧЕМ 1 СОБАКА'
if context {
@or(НАРЕЧИЕ:*{ /*СТЕПЕНЬ:СРАВН*/ },ПРИЛАГАТЕЛЬНОЕ:*{СТЕПЕНЬ:СРАВН})
_Запятая
СОЮЗ:ЧЕМ{}
NUMBER_
}
then
context { 0 .<ATTRIBUTE_EXC> 3 }
}
operator Comparative2Verb_4 : LINK_COMPARATIVE_ADV_2_VERB
{
// 'бегает быстрее, ЧЕМ она'
if context {
@or(НАРЕЧИЕ:*{ /*СТЕПЕНЬ:СРАВН*/ },ПРИЛАГАТЕЛЬНОЕ:*{СТЕПЕНЬ:СРАВН})
_Запятая
СОЮЗ:ЧЕМ{}
МЕСТОИМЕНИЕ:*{ ПАДЕЖ:ИМ }
}
then
context { 0 .<ATTRIBUTE_EXC> 3 }
}
operator Comparative2Verb_10 : LINK_COMPARATIVE_ADV_2_VERB
{
// 'бегает быстрее собаки'
if context {
@or(НАРЕЧИЕ:*{ /*СТЕПЕНЬ:СРАВН*/ },ПРИЛАГАТЕЛЬНОЕ:*{СТЕПЕНЬ:СРАВН})
СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:РОД }
}
then
context { 0 .<ATTRIBUTE_EXC> 1 }
}
operator Comparative2Verb_11 : LINK_COMPARATIVE_ADV_2_VERB
{
// 'бегает быстрее одной собаки'
if context {
@or(НАРЕЧИЕ:*{ /*СТЕПЕНЬ:СРАВН*/ },ПРИЛАГАТЕЛЬНОЕ:*{СТЕПЕНЬ:СРАВН})
ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:РОД }
}
then
context { 0 .<ATTRIBUTE_EXC> 1 }
}
operator Comparative2Verb_12 : LINK_COMPARATIVE_ADV_2_VERB
{
// 'бегает быстрее 2 собак'
if context { @or(НАРЕЧИЕ:*{ /*СТЕПЕНЬ:СРАВН*/ },ПРИЛАГАТЕЛЬНОЕ:*{СТЕПЕНЬ:СРАВН}) NUMBER_ }
then
context { 0 .<ATTRIBUTE_EXC> 1 }
}
operator Comparative2Verb_13 : LINK_COMPARATIVE_ADV_2_VERB
{
// 'бегает быстрее меня'
if context { @or(НАРЕЧИЕ:*{ /*СТЕПЕНЬ:СРАВН*/ },ПРИЛАГАТЕЛЬНОЕ:*{СТЕПЕНЬ:СРАВН}) МЕСТОИМЕНИЕ:*{ ПАДЕЖ:РОД } }
then
context { 0 .<ATTRIBUTE_EXC> 1 }
}
// Формально далее описываются не сравнительные формы наречий, но семантика у них именно такая.
operator Comparative2Verb_40 : LINK_COMPARATIVE_ADV_2_VERB
{
// 'КОШКА бегает так же быстро, КАК СОБАКА'
if context {
СОЮЗ:ТАК ЖЕ{}
@or(НАРЕЧИЕ:*{ /*СТЕПЕНЬ:СРАВН*/ },ПРИЛАГАТЕЛЬНОЕ:*{СТЕПЕНЬ:СРАВН})
_Запятая СОЮЗ:КАК{}
СУЩЕСТВИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ }
}
then
context { 1 .<ATTRIBUTE_LIKE> 4 }
}
operator Comparative2Verb_41 : LINK_COMPARATIVE_ADV_2_VERB
{
// 'КОШКА бегает так же быстро, КАК одна СОБАКА'
if context {
СОЮЗ:ТАК ЖЕ{}
@or(НАРЕЧИЕ:*{ /*СТЕПЕНЬ:СРАВН*/ },ПРИЛАГАТЕЛЬНОЕ:*{СТЕПЕНЬ:СРАВН})
_Запятая
СОЮЗ:КАК{}
ЧИСЛИТЕЛЬНОЕ:*{ ПАДЕЖ:ИМ }
}
then
context { 1 .<ATTRIBUTE_LIKE> 4 }
}
operator Comparative2Verb_42 : LINK_COMPARATIVE_ADV_2_VERB
{
// 'КОШКА бегает так же быстро, КАК 1 СОБАКА'
if context {
СОЮЗ:ТАК ЖЕ{}
@or(НАРЕЧИЕ:*{ /*СТЕПЕНЬ:СРАВН*/ },ПРИЛАГАТЕЛЬНОЕ:*{СТЕПЕНЬ:СРАВН})
_Запятая
СОЮЗ:КАК{}
NUMBER_
}
then
context { 1 .<ATTRIBUTE_LIKE> 4 }
}
operator Comparative2Verb_43 : LINK_COMPARATIVE_ADV_2_VERB
{
// 'КОШКА бегает так же быстро, КАК мы'
if context {
СОЮЗ:ТАК ЖЕ{}
@or(НАРЕЧИЕ:*{ /*СТЕПЕНЬ:СРАВН*/ },ПРИЛАГАТЕЛЬНОЕ:*{СТЕПЕНЬ:СРАВН})
_Запятая
СОЮЗ:КАК{}
МЕСТОИМЕНИЕ:*{ ПАДЕЖ:ИМ }
}
then
context { 1 .<ATTRIBUTE_LIKE> 4 }
}
}
| 'бегает быстрее, ЧЕМ СОБАКА' | {
if context {
_Запятая
}
then
}
operator Comparative2Verb_2 : LINK_COMPARATIVE_ADV_2_VERB
| 15,834,565 | [
1,
11,
145,
114,
145,
118,
145,
116,
145,
113,
145,
118,
146,
229,
225,
145,
114,
146,
238,
146,
228,
146,
229,
146,
227,
145,
118,
145,
118,
16,
225,
145,
105,
145,
248,
145,
255,
225,
145,
99,
145,
257,
145,
244,
145,
243,
145,
253,
145,
243,
11,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
288,
203,
225,
309,
819,
288,
203,
9506,
225,
389,
145,
250,
145,
113,
145,
128,
146,
242,
146,
229,
145,
113,
146,
242,
203,
9506,
289,
203,
282,
1508,
203,
289,
203,
203,
3726,
1286,
1065,
1535,
22,
16281,
67,
22,
294,
22926,
67,
4208,
2778,
12992,
67,
1880,
58,
67,
22,
67,
2204,
38,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1313161554/0xb9127241A2F1B08F6843F86adfac649694d014F8/sources/ReaperStrategyTrisolaris.sol | * @dev Tokens Used: {USDT} - Required for liquidity routing when doing swaps, in pair. {USN} - Required for liquidity and reward. {wNEAR} - Required for liquidity routing when doing swaps, in pair. {TRI} - Reward token for LP in MasterChef. {want} - Address of the LP token to farm. (lowercase name for FE compatibility)/* @dev Paths used to swap tokens: {triToUSNPath} - to swap {TRI} to {USN} (using TRISOLARIS_ROUTER)/* @dev Trisolaris variables. {poolId} - ID of pool in which to deposit LP tokens {usnIdx} - IDX of usn in stableswap {usdtIdx} - IDX of usdt in stableswap/* @dev Initializes the strategy. Sets parameters and saves routes. @notice see documentation for each variable above its respective declaration./ | {
__ReaperBaseStrategy_init(_vault, _treasury, _strategists, _multisigRoles);
want = _want;
poolId = _poolId;
triToUSNPath = [TRI, wNEAR, USN];
usnIdx = 2;
usdtIdx = 1;
}
| 16,945,660 | [
1,
5157,
10286,
30,
288,
3378,
9081,
97,
300,
10647,
364,
4501,
372,
24237,
7502,
1347,
9957,
1352,
6679,
16,
316,
3082,
18,
288,
3378,
50,
97,
300,
10647,
364,
4501,
372,
24237,
471,
19890,
18,
288,
91,
5407,
985,
97,
300,
10647,
364,
4501,
372,
24237,
7502,
1347,
9957,
1352,
6679,
16,
316,
3082,
18,
288,
6566,
97,
300,
534,
359,
1060,
1147,
364,
511,
52,
316,
13453,
39,
580,
74,
18,
288,
17369,
97,
300,
5267,
434,
326,
511,
52,
1147,
358,
284,
4610,
18,
261,
8167,
3593,
508,
364,
16439,
8926,
13176,
225,
16643,
1399,
358,
7720,
2430,
30,
288,
16857,
774,
3378,
50,
743,
97,
300,
358,
7720,
288,
6566,
97,
358,
288,
3378,
50,
97,
261,
9940,
22800,
19815,
985,
5127,
67,
1457,
1693,
654,
13176,
225,
840,
291,
355,
297,
291,
3152,
18,
288,
6011,
548,
97,
300,
1599,
434,
2845,
316,
1492,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
288,
203,
3639,
1001,
426,
7294,
2171,
4525,
67,
2738,
24899,
26983,
16,
389,
27427,
345,
22498,
16,
389,
701,
1287,
1486,
16,
389,
23978,
360,
6898,
1769,
203,
3639,
2545,
273,
389,
17369,
31,
203,
3639,
2845,
548,
273,
389,
6011,
548,
31,
203,
3639,
6882,
774,
3378,
50,
743,
273,
306,
6566,
16,
341,
5407,
985,
16,
11836,
50,
15533,
203,
3639,
584,
82,
4223,
273,
576,
31,
203,
3639,
584,
7510,
4223,
273,
404,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
pragma experimental ABIEncoderV2;
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { Ownable } from "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import { IAutoTrader } from "../../protocol/interfaces/IAutoTrader.sol";
import { ICallee } from "../../protocol/interfaces/ICallee.sol";
import { Account } from "../../protocol/lib/Account.sol";
import { Math } from "../../protocol/lib/Math.sol";
import { Monetary } from "../../protocol/lib/Monetary.sol";
import { Require } from "../../protocol/lib/Require.sol";
import { Types } from "../../protocol/lib/Types.sol";
import { OnlySolo } from "../helpers/OnlySolo.sol";
import { TypedSignature } from "../lib/TypedSignature.sol";
/**
* @title CanonicalOrders
* @author dYdX
*
* Allows for Canonical Orders to be used with dYdX
*/
contract CanonicalOrders is
Ownable,
OnlySolo,
IAutoTrader,
ICallee
{
using Math for uint256;
using SafeMath for uint256;
using Types for Types.Par;
using Types for Types.Wei;
// ============ Constants ============
bytes32 constant private FILE = "CanonicalOrders";
// EIP191 header for EIP712 prefix
bytes2 constant private EIP191_HEADER = 0x1901;
// EIP712 Domain Name value
string constant private EIP712_DOMAIN_NAME = "CanonicalOrders";
// EIP712 Domain Version value
string constant private EIP712_DOMAIN_VERSION = "1.0";
// Hash of the EIP712 Domain Separator Schema
/* solium-disable-next-line indentation */
bytes32 constant private EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"uint256 chainId,",
"address verifyingContract",
")"
));
// Hash of the EIP712 CanonicalOrder struct
/* solium-disable-next-line indentation */
bytes32 constant private EIP712_ORDER_STRUCT_SCHEMA_HASH = keccak256(abi.encodePacked(
"CanonicalOrder(",
"bytes32 flags,",
"uint256 baseMarket,",
"uint256 quoteMarket,",
"uint256 amount,",
"uint256 limitPrice,",
"uint256 triggerPrice,",
"uint256 limitFee,",
"address makerAccountOwner,",
"uint256 makerAccountNumber,",
"uint256 expiration",
")"
));
// Number of bytes in an Order struct plus number of bytes in a FillArgs struct
uint256 constant private NUM_ORDER_AND_FILL_BYTES = 416;
// Number of bytes in a typed signature
uint256 constant private NUM_SIGNATURE_BYTES = 66;
// The number of decimal places of precision in the price ratio of a triggerPrice
uint256 constant private PRICE_BASE = 10 ** 18;
// Bitmasks for the order.flag argument
bytes32 constant private IS_BUY_FLAG = bytes32(uint256(1));
bytes32 constant private IS_DECREASE_ONLY_FLAG = bytes32(uint256(1 << 1));
bytes32 constant private IS_NEGATIVE_FEE_FLAG = bytes32(uint256(1 << 2));
// ============ Enums ============
enum OrderStatus {
Null,
Approved,
Canceled
}
enum CallFunctionType {
Approve,
Cancel,
SetFillArgs
}
// ============ Structs ============
struct Order {
bytes32 flags; // salt, negativeFee, decreaseOnly, isBuy
uint256 baseMarket;
uint256 quoteMarket;
uint256 amount;
uint256 limitPrice;
uint256 triggerPrice;
uint256 limitFee;
address makerAccountOwner;
uint256 makerAccountNumber;
uint256 expiration;
}
struct FillArgs {
uint256 price;
uint128 fee;
bool isNegativeFee;
}
struct OrderInfo {
Order order;
FillArgs fill;
bytes32 orderHash;
}
struct OrderQueryOutput {
OrderStatus orderStatus;
uint256 filledAmount;
}
// ============ Events ============
event LogContractStatusSet(
bool operational
);
event LogTakerSet(
address taker
);
event LogCanonicalOrderCanceled(
bytes32 indexed orderHash,
address indexed canceler,
uint256 baseMarket,
uint256 quoteMarket
);
event LogCanonicalOrderApproved(
bytes32 indexed orderHash,
address indexed approver,
uint256 baseMarket,
uint256 quoteMarket
);
event LogCanonicalOrderFilled(
bytes32 indexed orderHash,
address indexed orderMaker,
uint256 fillAmount,
uint256 totalFilledAmount,
bool isBuy,
FillArgs fill
);
// ============ Immutable Storage ============
// Hash of the EIP712 Domain Separator data
bytes32 public EIP712_DOMAIN_HASH;
// ============ Mutable Storage ============
// true if this contract can process orders
bool public g_isOperational;
// order hash => filled amount (in baseAmount)
mapping (bytes32 => uint256) public g_filledAmount;
// order hash => status
mapping (bytes32 => OrderStatus) public g_status;
// stored fillArgs
FillArgs public g_fillArgs;
// required taker address
address public g_taker;
// ============ Constructor ============
constructor (
address soloMargin,
address taker,
uint256 chainId
)
public
OnlySolo(soloMargin)
{
g_isOperational = true;
g_taker = taker;
/* solium-disable-next-line indentation */
EIP712_DOMAIN_HASH = keccak256(abi.encode(
EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
keccak256(bytes(EIP712_DOMAIN_NAME)),
keccak256(bytes(EIP712_DOMAIN_VERSION)),
chainId,
address(this)
));
}
// ============ Admin Functions ============
/**
* The owner can shut down the exchange.
*/
function shutDown()
external
onlyOwner
{
g_isOperational = false;
emit LogContractStatusSet(false);
}
/**
* The owner can start back up the exchange.
*/
function startUp()
external
onlyOwner
{
g_isOperational = true;
emit LogContractStatusSet(true);
}
/**
* The owner can set the taker address.
*/
function setTakerAddress(
address taker
)
external
onlyOwner
{
g_taker = taker;
emit LogTakerSet(taker);
}
// ============ External Functions ============
/**
* Cancels an order.
*
* @param order The order to cancel
*/
function cancelOrder(
Order memory order
)
public
{
cancelOrderInternal(msg.sender, order);
}
/**
* Approves an order. Cannot already be canceled.
*
* @param order The order to approve
*/
function approveOrder(
Order memory order
)
public
{
approveOrderInternal(msg.sender, order);
}
// ============ Only-Solo Functions ============
/**
* Allows traders to make trades approved by this smart contract. The active trader's account is
* the takerAccount and the passive account (for which this contract approves trades
* on-behalf-of) is the makerAccount.
*
* @param inputMarketId The market for which the trader specified the original amount
* @param outputMarketId The market for which the trader wants the resulting amount specified
* @param makerAccount The account for which this contract is making trades
* @param takerAccount The account requesting the trade
* @param oldInputPar The par balance of the makerAccount for inputMarketId pre-trade
* @param newInputPar The par balance of the makerAccount for inputMarketId post-trade
* @param inputWei The change in token amount for the makerAccount for the inputMarketId
* @param data Arbitrary data passed in by the trader
* @return The AssetAmount for the makerAccount for the outputMarketId
*/
function getTradeCost(
uint256 inputMarketId,
uint256 outputMarketId,
Account.Info memory makerAccount,
Account.Info memory takerAccount,
Types.Par memory oldInputPar,
Types.Par memory newInputPar,
Types.Wei memory inputWei,
bytes memory data
)
public
onlySolo(msg.sender)
returns (Types.AssetAmount memory)
{
Require.that(
g_isOperational,
FILE,
"Contract is not operational"
);
OrderInfo memory orderInfo = getOrderInfo(data);
verifySignature(orderInfo, data);
verifyOrderInfo(
orderInfo,
makerAccount,
takerAccount,
inputMarketId,
outputMarketId,
inputWei
);
Types.AssetAmount memory assetAmount = getOutputAssetAmount(
inputMarketId,
outputMarketId,
inputWei,
orderInfo
);
if (isDecreaseOnly(orderInfo.order)) {
verifyDecreaseOnly(
oldInputPar,
newInputPar,
assetAmount,
makerAccount,
outputMarketId
);
}
return assetAmount;
}
/**
* Allows users to send this contract arbitrary data.
*
* param sender (unused)
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address /* sender */,
Account.Info memory accountInfo,
bytes memory data
)
public
onlySolo(msg.sender)
{
CallFunctionType cft = abi.decode(data, (CallFunctionType));
if (cft == CallFunctionType.SetFillArgs) {
FillArgs memory fillArgs;
(cft, fillArgs) = abi.decode(data, (CallFunctionType, FillArgs));
g_fillArgs = fillArgs;
} else {
Order memory order;
(cft, order) = abi.decode(data, (CallFunctionType, Order));
if (cft == CallFunctionType.Approve) {
approveOrderInternal(accountInfo.owner, order);
} else {
assert(cft == CallFunctionType.Cancel);
cancelOrderInternal(accountInfo.owner, order);
}
}
}
// ============ Getters ============
/**
* Returns the status and the filled amount of several orders.
*/
function getOrderStates(
bytes32[] memory orderHashes
)
public
view
returns(OrderQueryOutput[] memory)
{
uint256 numOrders = orderHashes.length;
OrderQueryOutput[] memory output = new OrderQueryOutput[](numOrders);
// for each order
for (uint256 i = 0; i < numOrders; i++) {
bytes32 orderHash = orderHashes[i];
output[i] = OrderQueryOutput({
orderStatus: g_status[orderHash],
filledAmount: g_filledAmount[orderHash]
});
}
return output;
}
// ============ Private Storage Functions ============
/**
* Cancels an order as long as it is not already canceled.
*/
function cancelOrderInternal(
address canceler,
Order memory order
)
private
{
Require.that(
canceler == order.makerAccountOwner,
FILE,
"Canceler must be maker"
);
bytes32 orderHash = getOrderHash(order);
g_status[orderHash] = OrderStatus.Canceled;
emit LogCanonicalOrderCanceled(
orderHash,
canceler,
order.baseMarket,
order.quoteMarket
);
}
/**
* Approves an order as long as it is not already approved or canceled.
*/
function approveOrderInternal(
address approver,
Order memory order
)
private
{
Require.that(
approver == order.makerAccountOwner,
FILE,
"Approver must be maker"
);
bytes32 orderHash = getOrderHash(order);
Require.that(
g_status[orderHash] != OrderStatus.Canceled,
FILE,
"Cannot approve canceled order",
orderHash
);
g_status[orderHash] = OrderStatus.Approved;
emit LogCanonicalOrderApproved(
orderHash,
approver,
order.baseMarket,
order.quoteMarket
);
}
// ============ Private Helper Functions ============
/**
* Parses the order, verifies that it is not expired or canceled, and verifies the signature.
*/
function getOrderInfo(
bytes memory data
)
private
returns (OrderInfo memory)
{
Require.that(
(
data.length == NUM_ORDER_AND_FILL_BYTES ||
data.length == NUM_ORDER_AND_FILL_BYTES + NUM_SIGNATURE_BYTES
),
FILE,
"Cannot parse order from data"
);
// load orderInfo from calldata
OrderInfo memory orderInfo;
(
orderInfo.order,
orderInfo.fill
) = abi.decode(data, (Order, FillArgs));
// load fillArgs from storage if price is zero
if (orderInfo.fill.price == 0) {
orderInfo.fill = g_fillArgs;
g_fillArgs = FillArgs({
price: 0,
fee: 0,
isNegativeFee: false
});
}
Require.that(
orderInfo.fill.price != 0,
FILE,
"FillArgs loaded price is zero"
);
orderInfo.orderHash = getOrderHash(orderInfo.order);
return orderInfo;
}
function verifySignature(
OrderInfo memory orderInfo,
bytes memory data
)
private
view
{
OrderStatus orderStatus = g_status[orderInfo.orderHash];
// verify valid signature or is pre-approved
if (orderStatus == OrderStatus.Null) {
bytes memory signature = parseSignature(data);
address signer = TypedSignature.recover(orderInfo.orderHash, signature);
Require.that(
orderInfo.order.makerAccountOwner == signer,
FILE,
"Order invalid signature",
orderInfo.orderHash
);
} else {
Require.that(
orderStatus != OrderStatus.Canceled,
FILE,
"Order canceled",
orderInfo.orderHash
);
assert(orderStatus == OrderStatus.Approved);
}
}
/**
* Verifies that the order is still fillable for the particular accounts and markets specified.
*/
function verifyOrderInfo(
OrderInfo memory orderInfo,
Account.Info memory makerAccount,
Account.Info memory takerAccount,
uint256 inputMarketId,
uint256 outputMarketId,
Types.Wei memory inputWei
)
private
view
{
// verify fill price
FillArgs memory fill = orderInfo.fill;
bool validPrice = isBuy(orderInfo.order)
? fill.price <= orderInfo.order.limitPrice
: fill.price >= orderInfo.order.limitPrice;
Require.that(
validPrice,
FILE,
"Fill invalid price"
);
// verify fill fee
bool validFee = isNegativeLimitFee(orderInfo.order)
? (fill.fee >= orderInfo.order.limitFee) && fill.isNegativeFee
: (fill.fee <= orderInfo.order.limitFee) || fill.isNegativeFee;
Require.that(
validFee,
FILE,
"Fill invalid fee"
);
// verify triggerPrice
if (orderInfo.order.triggerPrice > 0) {
uint256 currentPrice = getCurrentPrice(
orderInfo.order.baseMarket,
orderInfo.order.quoteMarket
);
Require.that(
isBuy(orderInfo.order)
? currentPrice >= orderInfo.order.triggerPrice
: currentPrice <= orderInfo.order.triggerPrice,
FILE,
"Order triggerPrice not triggered",
currentPrice
);
}
// verify expriy
Require.that(
orderInfo.order.expiration == 0 || orderInfo.order.expiration >= block.timestamp,
FILE,
"Order expired",
orderInfo.orderHash
);
// verify maker
Require.that(
makerAccount.owner == orderInfo.order.makerAccountOwner &&
makerAccount.number == orderInfo.order.makerAccountNumber,
FILE,
"Order maker account mismatch",
orderInfo.orderHash
);
// verify taker
Require.that(
takerAccount.owner == g_taker,
FILE,
"Order taker mismatch",
orderInfo.orderHash
);
// verify markets
Require.that(
(
orderInfo.order.baseMarket == outputMarketId &&
orderInfo.order.quoteMarket == inputMarketId
) || (
orderInfo.order.quoteMarket == outputMarketId &&
orderInfo.order.baseMarket == inputMarketId
),
FILE,
"Market mismatch",
orderInfo.orderHash
);
// verify inputWei is non-zero
Require.that(
!inputWei.isZero(),
FILE,
"InputWei is zero",
orderInfo.orderHash
);
// verify inputWei is positive if-and-only-if:
// 1) inputMarket is the baseMarket and the order is a buy order
// 2) inputMarket is the quoteMarket and the order is a sell order
Require.that(
inputWei.sign ==
((orderInfo.order.baseMarket == inputMarketId) == isBuy(orderInfo.order)),
FILE,
"InputWei sign mismatch",
orderInfo.orderHash
);
}
/**
* Verifies that the order is decreasing the size of the maker's position.
*/
function verifyDecreaseOnly(
Types.Par memory oldInputPar,
Types.Par memory newInputPar,
Types.AssetAmount memory assetAmount,
Account.Info memory makerAccount,
uint256 outputMarketId
)
private
view
{
// verify that the balance of inputMarketId is not increased
Require.that(
newInputPar.isZero()
|| (newInputPar.value <= oldInputPar.value && newInputPar.sign == oldInputPar.sign),
FILE,
"inputMarket not decreased"
);
// verify that the balance of outputMarketId is not increased
Types.Wei memory oldOutputWei = SOLO_MARGIN.getAccountWei(makerAccount, outputMarketId);
Require.that(
assetAmount.value == 0
|| (assetAmount.value <= oldOutputWei.value && assetAmount.sign != oldOutputWei.sign),
FILE,
"outputMarket not decreased"
);
}
/**
* Returns the AssetAmount for the outputMarketId given the order and the inputs. Updates the
* filled amount of the order in storage.
*/
function getOutputAssetAmount(
uint256 inputMarketId,
uint256 outputMarketId,
Types.Wei memory inputWei,
OrderInfo memory orderInfo
)
private
returns (Types.AssetAmount memory)
{
uint256 fee = orderInfo.fill.price.getPartial(orderInfo.fill.fee, PRICE_BASE);
uint256 adjustedPrice = (isBuy(orderInfo.order) == orderInfo.fill.isNegativeFee)
? orderInfo.fill.price.sub(fee)
: orderInfo.fill.price.add(fee);
uint256 outputAmount;
uint256 fillAmount;
if (orderInfo.order.quoteMarket == inputMarketId) {
outputAmount = inputWei.value.getPartial(PRICE_BASE, adjustedPrice);
fillAmount = outputAmount;
} else {
assert(orderInfo.order.quoteMarket == outputMarketId);
outputAmount = inputWei.value.getPartial(adjustedPrice, PRICE_BASE);
fillAmount = inputWei.value;
}
updateFilledAmount(orderInfo, fillAmount);
return Types.AssetAmount({
sign: !inputWei.sign,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: outputAmount
});
}
/**
* Increases the stored filled amount of the order by fillAmount.
* Returns the new total filled amount.
*/
function updateFilledAmount(
OrderInfo memory orderInfo,
uint256 fillAmount
)
private
{
uint256 oldFilledAmount = g_filledAmount[orderInfo.orderHash];
uint256 totalFilledAmount = oldFilledAmount.add(fillAmount);
Require.that(
totalFilledAmount <= orderInfo.order.amount,
FILE,
"Cannot overfill order",
orderInfo.orderHash,
oldFilledAmount,
fillAmount
);
g_filledAmount[orderInfo.orderHash] = totalFilledAmount;
emit LogCanonicalOrderFilled(
orderInfo.orderHash,
orderInfo.order.makerAccountOwner,
fillAmount,
totalFilledAmount,
isBuy(orderInfo.order),
orderInfo.fill
);
}
/**
* Returns the current price of baseMarket divided by the current price of quoteMarket. This
* value is multiplied by 10^18.
*/
function getCurrentPrice(
uint256 baseMarket,
uint256 quoteMarket
)
private
view
returns (uint256)
{
Monetary.Price memory basePrice = SOLO_MARGIN.getMarketPrice(baseMarket);
Monetary.Price memory quotePrice = SOLO_MARGIN.getMarketPrice(quoteMarket);
return basePrice.value.mul(PRICE_BASE).div(quotePrice.value);
}
// ============ Private Parsing Functions ============
/**
* Returns the EIP712 hash of an order.
*/
function getOrderHash(
Order memory order
)
private
view
returns (bytes32)
{
// compute the overall signed struct hash
/* solium-disable-next-line indentation */
bytes32 structHash = keccak256(abi.encode(
EIP712_ORDER_STRUCT_SCHEMA_HASH,
order
));
// compute eip712 compliant hash
/* solium-disable-next-line indentation */
return keccak256(abi.encodePacked(
EIP191_HEADER,
EIP712_DOMAIN_HASH,
structHash
));
}
/**
* Parses out a signature from call data.
*/
function parseSignature(
bytes memory data
)
private
pure
returns (bytes memory)
{
Require.that(
data.length == NUM_ORDER_AND_FILL_BYTES + NUM_SIGNATURE_BYTES,
FILE,
"Cannot parse signature from data"
);
bytes memory signature = new bytes(NUM_SIGNATURE_BYTES);
uint256 sigOffset = NUM_ORDER_AND_FILL_BYTES;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
let sigStart := add(data, sigOffset)
mstore(add(signature, 0x020), mload(add(sigStart, 0x20)))
mstore(add(signature, 0x040), mload(add(sigStart, 0x40)))
mstore(add(signature, 0x042), mload(add(sigStart, 0x42)))
}
return signature;
}
/**
* Returns true if the order is a buy order.
*/
function isBuy(
Order memory order
)
private
pure
returns (bool)
{
return (order.flags & IS_BUY_FLAG) != bytes32(0);
}
/**
* Returns true if the order is a decrease-only order.
*/
function isDecreaseOnly(
Order memory order
)
private
pure
returns (bool)
{
return (order.flags & IS_DECREASE_ONLY_FLAG) != bytes32(0);
}
/**
* Returns true if the order's limitFee is negative.
*/
function isNegativeLimitFee(
Order memory order
)
private
pure
returns (bool)
{
return (order.flags & IS_NEGATIVE_FEE_FLAG) != bytes32(0);
}
}
| verify valid signature or is pre-approved | function verifySignature(
OrderInfo memory orderInfo,
bytes memory data
)
private
view
{
OrderStatus orderStatus = g_status[orderInfo.orderHash];
if (orderStatus == OrderStatus.Null) {
bytes memory signature = parseSignature(data);
address signer = TypedSignature.recover(orderInfo.orderHash, signature);
Require.that(
orderInfo.order.makerAccountOwner == signer,
FILE,
"Order invalid signature",
orderInfo.orderHash
);
Require.that(
orderStatus != OrderStatus.Canceled,
FILE,
"Order canceled",
orderInfo.orderHash
);
assert(orderStatus == OrderStatus.Approved);
}
}
| 15,827,410 | [
1,
8705,
923,
3372,
578,
353,
675,
17,
25990,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3929,
5374,
12,
203,
3639,
4347,
966,
3778,
1353,
966,
16,
203,
3639,
1731,
3778,
501,
203,
565,
262,
203,
3639,
3238,
203,
3639,
1476,
203,
565,
288,
203,
3639,
4347,
1482,
1353,
1482,
273,
314,
67,
2327,
63,
1019,
966,
18,
1019,
2310,
15533,
203,
203,
3639,
309,
261,
1019,
1482,
422,
4347,
1482,
18,
2041,
13,
288,
203,
5411,
1731,
3778,
3372,
273,
1109,
5374,
12,
892,
1769,
203,
5411,
1758,
10363,
273,
13833,
5374,
18,
266,
3165,
12,
1019,
966,
18,
1019,
2310,
16,
3372,
1769,
203,
5411,
12981,
18,
19056,
12,
203,
7734,
1353,
966,
18,
1019,
18,
29261,
3032,
5541,
422,
10363,
16,
203,
7734,
7527,
16,
203,
7734,
315,
2448,
2057,
3372,
3113,
203,
7734,
1353,
966,
18,
1019,
2310,
203,
5411,
11272,
203,
5411,
12981,
18,
19056,
12,
203,
7734,
1353,
1482,
480,
4347,
1482,
18,
23163,
16,
203,
7734,
7527,
16,
203,
7734,
315,
2448,
17271,
3113,
203,
7734,
1353,
966,
18,
1019,
2310,
203,
5411,
11272,
203,
5411,
1815,
12,
1019,
1482,
422,
4347,
1482,
18,
31639,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x071f7792202cDDf08d103BAE5885FF04F812D632/sources/LNR_SWAP_LIST_V1.sol | checks to see if the token is for sale, if it is, facilitaes the sale
| function buyItem(bytes32 _name, address _destination) public nonReentrant payable { | 4,457,120 | [
1,
12366,
358,
2621,
309,
326,
1147,
353,
364,
272,
5349,
16,
309,
518,
353,
16,
5853,
330,
305,
22335,
326,
272,
5349,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
30143,
1180,
12,
3890,
1578,
389,
529,
16,
1758,
389,
10590,
13,
1071,
1661,
426,
8230,
970,
8843,
429,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x48b4C1ECdE2A54D37e31D1872dDD83965459183d/sources/CoinRacing.sol | SPDX-License-Identifier: MIT | pragma solidity >=0.5.16 <0.9.0;
| 4,347,399 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
683,
9454,
18035,
560,
1545,
20,
18,
25,
18,
2313,
411,
20,
18,
29,
18,
20,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Unlicense
pragma solidity 0.7.6;
import "hardhat/console.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import "@uniswap/v3-core/contracts/libraries/FullMath.sol";
import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
import "../interfaces/IVault.sol";
import "../interfaces/IUniversalVault.sol";
contract Hypervisor is IVault, IUniswapV3MintCallback, ERC20, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SignedSafeMath for int256;
uint256 public constant MILLIBASIS = 100000;
IUniswapV3Pool public pool;
IERC20 public token0;
IERC20 public token1;
uint24 public fee;
int24 public tickSpacing;
int24 public baseLower;
int24 public baseUpper;
int24 public limitLower;
int24 public limitUpper;
address public owner;
uint256 public maxTotalSupply;
uint256 public pendingFees0;
uint256 public pendingFees1;
/**
* @param _pool Underlying Uniswap V3 pool
* @param _owner The owner of the Hypervisor Contract
*/
constructor(
address _pool,
address _owner,
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper
) ERC20("Fungible Liquidity", "LIQ") {
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
fee = pool.fee();
tickSpacing = pool.tickSpacing();
owner = _owner;
baseLower = _baseLower;
baseUpper = _baseUpper;
limitLower = _limitLower;
limitUpper = _limitUpper;
maxTotalSupply = 0; // no cap
}
/**
* @notice Deposit tokens in proportion to the vault's holdings.
* @param deposit0 Amount of token0 to deposit
* @param deposit1 Amount of token1 to deposit
* @param to Recipient of shares
* @return shares Amount of shares distributed to sender
*/
function deposit(
uint256 deposit0,
uint256 deposit1,
address to
) external override nonReentrant returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0, "deposits must be nonzero");
require(to != address(0) && to != address(this), "to");
// update fess for inclusion in total pool amounts
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
uint256 price;
{
int24 currentTick = currentTick();
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick);
price = uint256(sqrtPrice).mul(uint256(sqrtPrice)).mul(1e18) >> (96 * 2);
}
// tokens which help balance the pool are given 100% of their token1
// value in liquidity tokens
// if the deposit worsens the ratio, dock the max - min amount 2%
uint256 deposit0PricedInToken1 = deposit0.mul(price).div(1e18);
(uint256 pool0, uint256 pool1) = getTotalAmounts();
uint256 pool0PricedInToken1 = pool0.mul(price).div(1e18);
if (pool0PricedInToken1.add(deposit0PricedInToken1) >= pool1 && deposit0PricedInToken1 > deposit1) {
shares = reduceByPercent(deposit0PricedInToken1.sub(deposit1), 2);
shares = shares.add(deposit1.mul(2));
} else if (pool0PricedInToken1 <= pool1 && deposit0PricedInToken1 < deposit1) {
shares = reduceByPercent(deposit1.sub(deposit0PricedInToken1), 2);
shares = shares.add(deposit0PricedInToken1.mul(2));
} else if (pool0PricedInToken1.add(deposit0PricedInToken1) < pool1.add(deposit1) && deposit0PricedInToken1 < deposit1) {
uint256 docked1 = pool1.add(deposit1).sub(pool0PricedInToken1.add(deposit0PricedInToken1));
shares = reduceByPercent(docked1, 2);
shares = deposit1.sub(docked1).add(deposit0PricedInToken1);
} else if (pool0PricedInToken1.add(deposit0PricedInToken1) > pool1.add(deposit1) && deposit0PricedInToken1 > deposit1) {
uint256 docked0 = pool0PricedInToken1.add(deposit0PricedInToken1).sub(pool1.add(deposit1));
shares = reduceByPercent(docked0, 2);
shares = deposit0PricedInToken1.sub(docked0).add(deposit1);
} else {
shares = deposit1.add(deposit0PricedInToken1);
}
if (deposit0 > 0) {
token0.safeTransferFrom(msg.sender, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(msg.sender, address(this), deposit1);
}
_mint(to, shares);
emit Deposit(msg.sender, to, shares, deposit0, deposit1);
// Check total supply cap not exceeded. A value of 0 means no limit.
require(maxTotalSupply == 0 || totalSupply() <= maxTotalSupply, "maxTotalSupply");
}
/**
* @notice Withdraw tokens in proportion to the vault's holdings.
* @param shares Shares burned by sender
* @param to Recipient of tokens
* @return amount0 Amount of token0 sent to recipient
* @return amount1 Amount of token1 sent to recipient
*/
function withdraw(
uint256 shares,
address to,
address from
) external override nonReentrant returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0), "to");
{
// Calculate how much liquidity to withdraw
uint128 baseLiquidity = _liquidityForShares(baseLower, baseUpper, shares);
uint128 limitLiquidity = _liquidityForShares(limitLower, limitUpper, shares);
// Withdraw liquidity from Uniswap pool
(uint256 base0, uint256 base1) =
_burnLiquidity(baseLower, baseUpper, baseLiquidity, to, false);
(uint256 limit0, uint256 limit1) =
_burnLiquidity(limitLower, limitUpper, limitLiquidity, to, false);
// Sum up total amounts sent to recipient
amount0 = base0.add(limit0);
amount1 = base1.add(limit1);
}
require(from == msg.sender || IUniversalVault(from).owner() == msg.sender, "Sender must own the tokens");
_burn(from, shares);
emit Withdraw(from, to, shares, amount0, amount1);
}
function exitPosition() external onlyOwner {
// update fess for inclusion in total pool amounts
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
// Withdraw all liquidity and collect all fees from Uniswap pool
(, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper);
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
pendingFees0 = feesBase0.add(feesLimit0);
pendingFees1 = feesBase1.add(feesLimit1);
_burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true);
}
function collectFees(address feeRecipient) external onlyOwner {
if(pendingFees0 > 0) token0.transfer(feeRecipient, pendingFees0.div(10));
if(pendingFees1 > 0) token1.transfer(feeRecipient, pendingFees1.div(10));
}
function enterPosition(int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper) external onlyOwner {
uint256 balance0 = token0.balanceOf(address(this));
uint256 balance1 = token1.balanceOf(address(this));
baseLower = _baseLower;
baseUpper = _baseUpper;
uint128 baseLiquidity = _liquidityForAmounts(baseLower, baseUpper, balance0, balance1);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
balance0 = token0.balanceOf(address(this));
balance1 = token1.balanceOf(address(this));
limitLower = _limitLower;
limitUpper = _limitUpper;
uint128 limitLiquidity = _liquidityForAmounts(limitLower, limitUpper, balance0, balance1);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
/**
* @notice Update vault's positions arbitrarily
*/
function rebalance(int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address feeRecipient) external override nonReentrant onlyOwner {
// Check that ranges are not the same
assert(_baseLower != _limitLower || _baseUpper != _limitUpper);
// update fess for inclusion in total pool amounts
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
// Withdraw all liquidity and collect all fees from Uniswap pool
(, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper);
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
uint256 fees0 = feesBase0.add(feesLimit0);
uint256 fees1 = feesBase1.add(feesLimit1);
console.log(fees0);
console.log(fees1);
_burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true);
// transfer 10% of fees for VISR buybacks
if(fees0 > 0) token0.transfer(feeRecipient, fees0.div(10));
if(fees1 > 0) token1.transfer(feeRecipient, fees1.div(10));
uint256 balance0 = token0.balanceOf(address(this));
uint256 balance1 = token1.balanceOf(address(this));
int24 currentTick = currentTick();
emit Rebalance(currentTick, balance0, balance1, fees0, fees1, totalSupply());
baseLower = _baseLower;
baseUpper = _baseUpper;
baseLiquidity = _liquidityForAmounts(baseLower, baseUpper, balance0, balance1);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
balance0 = token0.balanceOf(address(this));
balance1 = token1.balanceOf(address(this));
limitLower = _limitLower;
limitUpper = _limitUpper;
limitLiquidity = _liquidityForAmounts(limitLower, limitUpper, balance0, balance1);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address payer
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(payer)
);
}
}
/// @param collectAll Whether to also collect all accumulated fees.
function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
// Burn liquidity
(uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity);
// Collect amount owed
uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0);
uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1);
}
}
}
/// @dev Convert shares into amount of liquidity. Shouldn't be called
/// when total supply is 0.
function _liquidityForShares(
int24 tickLower,
int24 tickUpper,
uint256 shares
) internal view returns (uint128) {
(uint128 position,,) = _position(tickLower, tickUpper);
return _uint128Safe(uint256(position).mul(shares).div(totalSupply()));
}
/// @dev Amount of liquidity deposited by vault into Uniswap V3 pool for a
/// certain range.
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1)
{
bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper));
(liquidity, , , tokensOwed0, tokensOwed1) = pool.positions(positionKey);
}
/// @dev Callback for Uniswap V3 pool mint.
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (payer == address(this)) {
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
} else {
if (amount0 > 0) token0.safeTransferFrom(payer, msg.sender, amount0);
if (amount1 > 0) token1.safeTransferFrom(payer, msg.sender, amount1);
}
}
/**
* @notice Calculate total holdings of token0 and token1, or how much of
* each token this vault would hold if it withdrew all its liquidity.
*/
function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) {
(, uint256 base0, uint256 base1) = getBasePosition();
(, uint256 limit0, uint256 limit1) = getLimitPosition();
total0 = token0.balanceOf(address(this)).add(base0).add(limit0);
total1 = token1.balanceOf(address(this)).add(base1).add(limit1);
}
/**
* @notice Calculate liquidity and equivalent token amounts of base order.
*/
function getBasePosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(baseLower, baseUpper);
(amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
/**
* @notice Calculate liquidity and equivalent token amounts of limit order.
*/
function getLimitPosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(limitLower, limitUpper);
(amount0, amount1) = _amountsForLiquidity(limitLower, limitUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
/// @dev Wrapper around `getAmountsForLiquidity()` for convenience.
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
/// @dev Wrapper around `getLiquidityForAmounts()` for convenience.
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
/// @dev Get current tick from pool
function currentTick() internal view returns (int24 currentTick) {
(, currentTick, , , , , ) = pool.slot0();
}
function _uint128Safe(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyOwner {
maxTotalSupply = _maxTotalSupply;
}
function reduceByPercent(uint256 quantity, uint256 percent) internal view returns (uint256) {
return quantity.mul(MILLIBASIS.mul(100 - percent)).div(MILLIBASIS.mul(100));
}
modifier onlyOwner {
require(msg.sender == owner, "only owner");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity 0.7.6;
interface IVault {
function deposit(
uint256,
uint256,
address
) external returns (uint256);
function withdraw(
uint256,
address,
address
) external returns (uint256, uint256);
function rebalance(int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address feeRecipient) external;
function getTotalAmounts() external view returns (uint256, uint256);
event Deposit(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Withdraw(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Rebalance(
int24 tick,
uint256 totalAmount0,
uint256 totalAmount1,
uint256 feeAmount0,
uint256 feeAmount1,
uint256 totalSupply
);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
interface IUniversalVault {
/* user events */
event Locked(address delegate, address token, uint256 amount);
event Unlocked(address delegate, address token, uint256 amount);
event RageQuit(address delegate, address token, bool notified, string reason);
/* data types */
struct LockData {
address delegate;
address token;
uint256 balance;
}
/* initialize function */
function initialize() external;
/* user functions */
function lock(
address token,
uint256 amount,
bytes calldata permission
) external;
function unlock(
address token,
uint256 amount,
bytes calldata permission
) external;
function rageQuit(address delegate, address token)
external
returns (bool notified, string memory error);
function transferERC20(
address token,
address to,
uint256 amount
) external;
function transferETH(address to, uint256 amount) external payable;
/* pure functions */
function calculateLockID(address delegate, address token)
external
pure
returns (bytes32 lockID);
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) external view returns (bytes32 permissionHash);
function getNonce() external view returns (uint256 nonce);
function owner() external view returns (address ownerAddress);
function getLockSetCount() external view returns (uint256 count);
function getLockAt(uint256 index) external view returns (LockData memory lockData);
function getBalanceDelegated(address token, address delegate)
external
view
returns (uint256 balance);
function getBalanceLocked(address token) external view returns (uint256 balance);
function checkBalances() external view returns (bool validity);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
| * @notice Calculate liquidity and equivalent token amounts of base order./ | function getBasePosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(baseLower, baseUpper);
(amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
| 1,293,251 | [
1,
8695,
4501,
372,
24237,
471,
7680,
1147,
30980,
434,
1026,
1353,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8297,
2555,
1435,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
203,
5411,
2254,
10392,
4501,
372,
24237,
16,
203,
5411,
2254,
5034,
3844,
20,
16,
203,
5411,
2254,
5034,
3844,
21,
203,
3639,
262,
203,
565,
288,
203,
3639,
261,
11890,
10392,
1754,
48,
18988,
24237,
16,
2254,
10392,
2430,
3494,
329,
20,
16,
2254,
10392,
2430,
3494,
329,
21,
13,
273,
389,
3276,
12,
1969,
4070,
16,
1026,
5988,
1769,
203,
3639,
261,
8949,
20,
16,
3844,
21,
13,
273,
389,
8949,
28388,
48,
18988,
24237,
12,
1969,
4070,
16,
1026,
5988,
16,
1754,
48,
18988,
24237,
1769,
203,
3639,
3844,
20,
273,
3844,
20,
18,
1289,
12,
11890,
5034,
12,
7860,
3494,
329,
20,
10019,
203,
3639,
3844,
21,
273,
3844,
21,
18,
1289,
12,
11890,
5034,
12,
7860,
3494,
329,
21,
10019,
203,
3639,
4501,
372,
24237,
273,
1754,
48,
18988,
24237,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0xD5B88558a807D5F394e0F22743D4F1C5eAb76B6F/sources/project_/contracts/payment-token/PaymentTokenRegistry.sol | * @dev See {IPaymentTokenRegistry-isAllowedPaymentToken}./ | {
return
_paymentTokens.contains(token) ||
_collectionPaymentTokens[collectionAddress].contains(token);
}
| 4,694,214 | [
1,
9704,
288,
2579,
2955,
1345,
4243,
17,
291,
5042,
6032,
1345,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
327,
203,
5411,
389,
9261,
5157,
18,
12298,
12,
2316,
13,
747,
203,
5411,
389,
5548,
6032,
5157,
63,
5548,
1887,
8009,
12298,
12,
2316,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
contract DecentralizationSmartGames{
using SafeMath for uint256;
string public constant name = "Decentralization Smart Games";
string public constant symbol = "DSG";
uint8 public constant decimals = 18;
uint256 public constant tokenPrice = 0.00065 ether;
uint256 public totalSupply; /* Total number of existing DSG tokens */
uint256 public divPerTokenPool; /* Trigger for calculating dividends on "Pool dividends" program */
uint256 public divPerTokenGaming; /* Trigger for calculating dividends on "Gaming dividends" program */
uint256 public developmentBalance; /* Balance that is used to support the project and games development */
uint256 public charityBalance; /* Balance that is used for charity */
address[2] public owners; /* Addresses of the contract owners */
address[2] public candidates; /* Addresses of the future contract owners */
/**Fee public fee - Structure where all percentages of the distribution of incoming funds are stored
* uint8 fee.r0 - First referrer - 6%
* uint8 fee.r1 - Second referrer - 4%
* uint8 fee.r2 - Third referrer - 3%
* uint8 fee.r3 - Fourth referrer - 2%
* uint8 fee.r4 - Fifth referrer - 1%
* uint8 fee.charity - Charity - 1%
* uint8 fee.development - For game development and project support - 18%
* uint8 fee.buy - For buying DSG tokens - 65%
*/
Fee public fee = Fee(6,4,3,2,1,1,18,65);
/**Dividends public totalDividends - Structure where general dividend payments are kept
* uint256 totalDividends.referrer - Referrer Dividends
* uint256 totalDividends.gaming - Gaming Dividends
* uint256 totalDividends.pool - Pool Dividends
*/
Dividends public totalDividends = Dividends(0,0,0);
mapping (address => mapping (address => uint256)) private allowed;
/**mapping (address => Account) private account - Investors accounts data
* uint256 account[address].tokenBalance - Number of DSG tokens on balance
* uint256 account[address].ethereumBalance - The amount of ETH on balance (dividends)
* uint256 account[address].lastDivPerTokenPool - The trigger of last dividend payment upon the "Pool dividends" program
* uint256 account[address].lastDivPerTokenGaming - The trigger of last dividend payment upon the "Gaming dividends" program
* uint256 account[address].totalDividendsReferrer - Total amount of dividends upon the "Referrer dividends" program
* uint256 account[address].totalDividendsGaming - Total amount of dividends upon the "Gaming dividends" program
* uint256 account[address].totalDividendsPool -Total amount of dividends upon the "Pool dividends" program
* address[5] account[address].referrer - Array of all the referrers
* bool account[address].active - True, if the account is active
*/
mapping (address => Account) public account;
mapping (address => bool) public games; /* The list of contracts from which dividends are allowed */
struct Account {
uint256 tokenBalance;
uint256 ethereumBalance;
uint256 lastDivPerTokenPool;
uint256 lastDivPerTokenGaming;
uint256 totalDividendsReferrer;
uint256 totalDividendsGaming;
uint256 totalDividendsPool;
address[5] referrer;
bool active;
}
struct Fee{
uint8 r1;
uint8 r2;
uint8 r3;
uint8 r4;
uint8 r5;
uint8 charity;
uint8 development;
uint8 buy;
}
struct Dividends{
uint256 referrer;
uint256 gaming;
uint256 pool;
}
/* Allowed if the address is not 0x */
modifier check0x(address address0x) {
require(address0x != address(0), "Address is 0x");
_;
}
/* Allowed if on balance of DSG tokens >= amountDSG */
modifier checkDSG(uint256 amountDSG) {
require(account[msg.sender].tokenBalance >= amountDSG, "You don't have enough DSG on balance");
_;
}
/* Allowed if on balance ETH >= amountETH */
modifier checkETH(uint256 amountETH) {
require(account[msg.sender].ethereumBalance >= amountETH, "You don't have enough ETH on balance");
_;
}
/* Allowed if the function is called by one the contract owners */
modifier onlyOwners() {
require(msg.sender == owners[0] || msg.sender == owners[1], "You are not owner");
_;
}
/* Allowed if the sale is still active */
modifier sellTime() {
require(now <= 1560211200, "The sale is over");
_;
}
/* Dividends upon the "Pool Dividends" program are being paid */
/* Dividends upon the "Gaming Dividends" program are being paid */
modifier payDividends(address sender) {
uint256 poolDividends = getPoolDividends();
uint256 gamingDividends = getGamingDividends();
if(poolDividends > 0 && account[sender].active == true){
account[sender].totalDividendsPool = account[sender].totalDividendsPool.add(poolDividends);
account[sender].ethereumBalance = account[sender].ethereumBalance.add(poolDividends);
}
if(gamingDividends > 0 && account[sender].active == true){
account[sender].totalDividendsGaming = account[sender].totalDividendsGaming.add(gamingDividends);
account[sender].ethereumBalance = account[sender].ethereumBalance.add(gamingDividends);
}
_;
account[sender].lastDivPerTokenPool = divPerTokenPool;
account[sender].lastDivPerTokenGaming = divPerTokenGaming;
}
/**We assign two contract owners, whose referrers are from the same address
* In the same manner we activate their accounts
*/
constructor(address owner2) public{
address owner1 = msg.sender;
owners[0] = owner1;
owners[1] = owner2;
account[owner1].active = true;
account[owner2].active = true;
account[owner1].referrer = [owner1, owner1, owner1, owner1, owner1];
account[owner2].referrer = [owner2, owner2, owner2, owner2, owner2];
}
/**buy() - the function of buying DSG tokens.
* It is active only during the time interval specified in sellTime()
* Dividends upon Pool Dividends program are being paid
* Dividends upon the Gaming Dividends program are being paid
* address referrerAddress - The address of the referrer who invited to the program
* require - Minimum purchase is 100 DSG or 0.1 ETH
*/
function buy(address referrerAddress) payDividends(msg.sender) sellTime public payable
{
require(msg.value >= 0.1 ether, "Minimum investment is 0.1 ETH");
uint256 forTokensPurchase = msg.value.mul(fee.buy).div(100); /* 65% */
uint256 forDevelopment = msg.value.mul(fee.development).div(100); /* 18% */
uint256 forCharity = msg.value.mul(fee.charity).div(100); /* 1% */
uint256 tokens = forTokensPurchase.mul(10 ** uint(decimals)).div(tokenPrice); /* The number of DSG tokens is counted (1ETH = 1000 DSG) */
_setReferrer(referrerAddress, msg.sender); /* Assigning of referrers */
_mint(msg.sender, tokens); /* We create new DSG tokens and add to balance */
_setProjectDividends(forDevelopment, forCharity); /* ETH is accrued to the project balances (18%, 1%) */
_distribution(msg.sender, msg.value.mul(fee.r1).div(100), 0); /* Dividends are accrued to the first refferer - 6% */
_distribution(msg.sender, msg.value.mul(fee.r2).div(100), 1); /* Dividends are accrued to the second refferer - 4% */
_distribution(msg.sender, msg.value.mul(fee.r3).div(100), 2); /* Dividends are accrued to the third refferer - 3% */
_distribution(msg.sender, msg.value.mul(fee.r4).div(100), 3); /* Dividends are accrued to the fourth refferer - 2% */
_distribution(msg.sender, msg.value.mul(fee.r5).div(100), 4); /* Dividends are accrued to the fifth referrer - 1% */
emit Buy(msg.sender, msg.value, tokens, totalSupply, now);
}
/**reinvest() - dividends reinvestment function.
* It is active only during the time interval specified in sellTime()
* Dividends upon the Pool Dividends and Gaming Dividends programs are being paid - payDividends(msg.sender)
* Checking whether the investor has a given amount of ETH in the contract - checkETH(amountEthereum)
* address amountEthereum - The amount of ETH sent for reinvestment (dividends)
*/
function reinvest(uint256 amountEthereum) payDividends(msg.sender) checkETH(amountEthereum) sellTime public
{
uint256 tokens = amountEthereum.mul(10 ** uint(decimals)).div(tokenPrice); /* The amount of DSG tokens is counted (1ETH = 1000 DSG) */
_mint(msg.sender, tokens); /* We create DSG tokens and add to the balance */
account[msg.sender].ethereumBalance = account[msg.sender].ethereumBalance.sub(amountEthereum);/* The amount of ETH from the investor is decreased */
emit Reinvest(msg.sender, amountEthereum, tokens, totalSupply, now);
}
/**reinvest() - dividends reinvestment function.
* Checking whether there are enough DSG tokens on balance - checkDSG(amountTokens)
* Dividends upon the Pool Dividends and Gaming Dividends program are being paid - payDividends(msg.sender)
* address amountEthereum - The amount of ETH sent for reinvestment (dividends)
* require - Checking whether the investor has a given amount of ETH in the contract
*/
function sell(uint256 amountTokens) payDividends(msg.sender) checkDSG(amountTokens) public
{
uint256 ethereum = amountTokens.mul(tokenPrice).div(10 ** uint(decimals));/* Counting the number of ETH (1000 DSG = 1ETH) */
account[msg.sender].ethereumBalance = account[msg.sender].ethereumBalance.add(ethereum);
_burn(msg.sender, amountTokens);/* Tokens are burnt */
emit Sell(msg.sender, amountTokens, ethereum, totalSupply, now);
}
/**withdraw() - the function of ETH withdrawal from the contract
* Dividends upon the Pool Dividends and Gaming Dividends programs are being paid - payDividends(msg.sender)
* Checking whether the investor has a given amount of ETH in the contract - checkETH(amountEthereum)
* address amountEthereum - The amount of ETH requested for withdrawal
*/
function withdraw(uint256 amountEthereum) payDividends(msg.sender) checkETH(amountEthereum) public
{
msg.sender.transfer(amountEthereum); /* ETH is sent */
account[msg.sender].ethereumBalance = account[msg.sender].ethereumBalance.sub(amountEthereum);/* Decreasing the amount of ETH from the investor */
emit Withdraw(msg.sender, amountEthereum, now);
}
/**gamingDividendsReception() - function that receives and distributes dividends upon the "Gaming Dividends" program
* require - if the address of the game is not registered in mapping games, the transaction will be declined
*/
function gamingDividendsReception() payable external{
require(getGame(msg.sender) == true, "Game not active");
uint256 eth = msg.value;
uint256 forDevelopment = eth.mul(19).div(100); /* To support the project - 19% */
uint256 forInvesotrs = eth.mul(80).div(100); /* To all DSG holders - 80% */
uint256 forCharity = eth.div(100); /* For charity - 1% */
_setProjectDividends(forDevelopment, forCharity); /* Dividends for supporting the projects are distributed */
_setGamingDividends(forInvesotrs); /* Gaming dividends are distributed */
}
/**_distribution() - function of dividends distribution upon the "Referrer Dividends" program
* With a mimimum purchase ranging from 100 to 9999 DSG
* Only the first level of the referral program is open and a floating percentage is offered, which depends on the amount of investment.
* Formula - ETH * DSG / 10000 = %
* ETH - the amount of Ethereum, which the investor should have received if the balance had been >= 10000 DSG (6%)
* DSG - the amount of tokens on the referrer's balance, which accrues interest
* 10000 - minimum amount of tokens when all the percentage levels are open
* - The first level is a floating percentage depending on the amount of holding
* - The second level - for all upon the "Pool dividends" program
* - The third level - for all upon the "Pool dividends" program
* - The fourth level - for all upon the "Pool dividends" program
* - The fifth level - for all upon the "Pool dividends" program
* With 10000 DSG on balance and more the entire referral system will be activated and the investor will receive all interest from all levels
* The function automatically checks the investor's DSG balance at the time of dividends distribution, this that referral
* program can be fully activated or deactivated automatically depending on the DSG balance at the time of distribution
* address senderAddress - the address of referral that sends dividends to his referrer
* uint256 eth - the amount of ETH which referrer should send to the referrer
* uint8 k - the number of referrer
*/
function _distribution(address senderAddress, uint256 eth, uint8 k) private{
address referrer = account[senderAddress].referrer[k];
uint256 referrerBalance = account[referrer].tokenBalance;
uint256 senderTokenBalance = account[senderAddress].tokenBalance;
uint256 minReferrerBalance = 10000e18;
if(referrerBalance >= minReferrerBalance){
_setReferrerDividends(referrer, eth);/* The interest is sent to the referrer */
}
else if(k == 0 && referrerBalance < minReferrerBalance && referrer != address(0)){
uint256 forReferrer = eth.mul(referrerBalance).div(minReferrerBalance);/* The floating percentage is counted */
uint256 forPool = eth.sub(forReferrer);/* Amount for Pool Dividends (all DSG holders) */
_setReferrerDividends(referrer, forReferrer);/* The referrer is sent his interest */
_setPoolDividends(forPool, senderTokenBalance);/* Dividends are paid to all the DSG token holders */
}
else{
_setPoolDividends(eth, senderTokenBalance);/* If the refferal is 0x - Dividends are paid to all the DSG token holders */
}
}
/* _setReferrerDividends() - the function which sends referrer his dividends */
function _setReferrerDividends(address referrer, uint256 eth) private {
account[referrer].ethereumBalance = account[referrer].ethereumBalance.add(eth);
account[referrer].totalDividendsReferrer = account[referrer].totalDividendsReferrer.add(eth);
totalDividends.referrer = totalDividends.referrer.add(eth);
}
/**_setReferrer() - the function which assigns referrers to the buyer
* address referrerAddress - the address of referrer who invited the investor to the project
* address senderAddress - the buyer's address
* The function assigns referrers only once when buying tokens
* Referrers can not be changed
* require(referrerAddress != senderAddress) - Checks whether the buyer is not a referrer himself
* require(account[referrerAddress].active == true || referrerAddress == address(0))
* Checks whether the referrer exists in the project
*/
function _setReferrer(address referrerAddress, address senderAddress) private
{
if(account[senderAddress].active == false){
require(referrerAddress != senderAddress, "You can't be referrer for yourself");
require(account[referrerAddress].active == true || referrerAddress == address(0), "Your referrer was not found in the contract");
account[senderAddress].referrer = [
referrerAddress, /* The referrer who invited the investor */
account[referrerAddress].referrer[0],
account[referrerAddress].referrer[1],
account[referrerAddress].referrer[2],
account[referrerAddress].referrer[3]
];
account[senderAddress].active = true; /* The account is activated */
emit Referrer(
senderAddress,
account[senderAddress].referrer[0],
account[senderAddress].referrer[1],
account[senderAddress].referrer[2],
account[senderAddress].referrer[3],
account[senderAddress].referrer[4],
now
);
}
}
/**setRef_setProjectDividendserrer() - the function of dividends payment to support the project
* uint256 forDevelopment - To support the project - 18%
* uint256 forCharity - For charity - 1%
*/
function _setProjectDividends(uint256 forDevelopment, uint256 forCharity) private{
developmentBalance = developmentBalance.add(forDevelopment);
charityBalance = charityBalance.add(forCharity);
}
/**_setPoolDividends() - the function of uniform distribution of dividends to all DSG holders upon the "Pool Dividends" program
* During the distribution of dividends, the amount of tokens that are on the buyer's balance is not taken into account,
* since he does not participate in the distribution of dividends
* uint256 amountEthereum - the amount of ETH which should be distributed to all DSG holders
* uint256 userTokens - the amount of DSG that is on the buyer's balance
*/
function _setPoolDividends(uint256 amountEthereum, uint256 userTokens) private{
if(amountEthereum > 0){
divPerTokenPool = divPerTokenPool.add(amountEthereum.mul(10 ** uint(decimals)).div(totalSupply.sub(userTokens)));
totalDividends.pool = totalDividends.pool.add(amountEthereum);
}
}
/**_setGamingDividends() - the function of uniform distribution of dividends to all DSG holders upon the "Gaming Dividends" program
* uint256 amountEthereum - the amount of ETH which should be distributed to all DSG holders
*/
function _setGamingDividends(uint256 amountEthereum) private{
if(amountEthereum > 0){
divPerTokenGaming = divPerTokenGaming.add(amountEthereum.mul(10 ** uint(decimals)).div(totalSupply));
totalDividends.gaming = totalDividends.gaming.add(amountEthereum);
}
}
/**setGame() - the function of adding a new address of the game contract, from which you can receive dividends
* address gameAddress - the address of the game contract
* bool active - if TRUE, the dividends can be received
*/
function setGame(address gameAddress, bool active) public onlyOwners returns(bool){
games[gameAddress] = active;
return true;
}
/**getPoolDividends() - the function of calculating dividends for the investor upon the "Pool Dividends" program
* returns(uint256) - the amount of ETH that was counted to the investor is returned
* and which has not been paid to him yet
*/
function getPoolDividends() public view returns(uint256)
{
uint newDividendsPerToken = divPerTokenPool.sub(account[msg.sender].lastDivPerTokenPool);
return account[msg.sender].tokenBalance.mul(newDividendsPerToken).div(10 ** uint(decimals));
}
/**getGameDividends() - the function of calculating dividends for the investor upon the "Gaming Dividends" program
* returns(uint256) - the amount of ETH that was counted to the investor is returned,
* and which has not been paid to him yet
*/
function getGamingDividends() public view returns(uint256)
{
uint newDividendsPerToken = divPerTokenGaming.sub(account[msg.sender].lastDivPerTokenGaming);
return account[msg.sender].tokenBalance.mul(newDividendsPerToken).div(10 ** uint(decimals));
}
/* getAccountData() - the function that returns all the data of the investor */
function getAccountData() public view returns(
uint256 tokenBalance,
uint256 ethereumBalance,
uint256 lastDivPerTokenPool,
uint256 lastDivPerTokenGaming,
uint256 totalDividendsPool,
uint256 totalDividendsReferrer,
uint256 totalDividendsGaming,
address[5] memory referrer,
bool active)
{
return(
account[msg.sender].tokenBalance,
account[msg.sender].ethereumBalance,
account[msg.sender].lastDivPerTokenPool,
account[msg.sender].lastDivPerTokenGaming,
account[msg.sender].totalDividendsPool,
account[msg.sender].totalDividendsReferrer,
account[msg.sender].totalDividendsGaming,
account[msg.sender].referrer,
account[msg.sender].active
);
}
/* getContractBalance() - the function that returns a contract balance */
function getContractBalance() view public returns (uint256) {
return address(this).balance;
}
/* getGame() - the function that checks whether the game is active or not. If TRUE - the game is active. If FALSE - the game is not active */
function getGame(address gameAddress) view public returns (bool) {
return games[gameAddress];
}
/* transferOwnership() - the function that assigns the future founder of the contract */
function transferOwnership(address candidate, uint8 k) check0x(candidate) onlyOwners public
{
candidates[k] = candidate;
}
/* confirmOwner() - the function that confirms the new founder of the contract and assigns him */
function confirmOwner(uint8 k) public
{
require(msg.sender == candidates[k], "You are not candidate");
owners[k] = candidates[k];
delete candidates[k];
}
/* charitytWithdraw() - the function of withdrawal for charity */
function charitytWithdraw(address recipient) onlyOwners check0x(recipient) public
{
recipient.transfer(charityBalance);
delete charityBalance;
}
/* developmentWithdraw() - the function of withdrawal for the project support */
function developmentWithdraw(address recipient) onlyOwners check0x(recipient) public
{
recipient.transfer(developmentBalance);
delete developmentBalance;
}
/* balanceOf() - the function that returns the amount of DSG tokens on balance (ERC20 standart) */
function balanceOf(address owner) public view returns(uint256)
{
return account[owner].tokenBalance;
}
/* allowance() - the function that checks how much spender can spend tokens of the owner user (ERC20 standart) */
function allowance(address owner, address spender) public view returns(uint256)
{
return allowed[owner][spender];
}
/* transferTo() - the function sends DSG tokens to another user (ERC20 standart) */
function transfer(address to, uint256 value) public returns(bool)
{
_transfer(msg.sender, to, value);
return true;
}
/* transferTo() - the function that allows the user to spend n-number of tokens for spender (ERC20 standart) */
function approve(address spender, uint256 value) check0x(spender) checkDSG(value) public returns(bool)
{
allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/* transferFrom() - the function sends tokens from one address to another, only to the address that gave the permission (ERC20 standart) */
function transferFrom(address from, address to, uint256 value) public returns(bool)
{
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, allowed[from][msg.sender]);
return true;
}
/* _transfer() - the function of tokens sending (ERC20 standart) */
function _transfer(address from, address to, uint256 value) payDividends(from) payDividends(to) checkDSG(value) check0x(to) private
{
account[from].tokenBalance = account[from].tokenBalance.sub(value);
account[to].tokenBalance = account[to].tokenBalance.add(value);
if(account[to].active == false) account[to].active = true;
emit Transfer(from, to, value);
}
/* transferFrom() - the function of tokens creating (ERC20 standart) */
function _mint(address customerAddress, uint256 value) check0x(customerAddress) private
{
totalSupply = totalSupply.add(value);
account[customerAddress].tokenBalance = account[customerAddress].tokenBalance.add(value);
emit Transfer(address(0), customerAddress, value);
}
/* transferFrom() - the function of tokens _burning (ERC20 standart) */
function _burn(address customerAddress, uint256 value) check0x(customerAddress) private
{
totalSupply = totalSupply.sub(value);
account[customerAddress].tokenBalance = account[customerAddress].tokenBalance.sub(value);
emit Transfer(customerAddress, address(0), value);
}
event Buy(
address indexed customerAddress,
uint256 inputEthereum,
uint256 outputToken,
uint256 totalSupply,
uint256 timestamp
);
event Sell(
address indexed customerAddress,
uint256 amountTokens,
uint256 outputEthereum,
uint256 totalSupply,
uint256 timestamp
);
event Reinvest(
address indexed customerAddress,
uint256 amountEthereum,
uint256 outputToken,
uint256 totalSupply,
uint256 timestamp
);
event Withdraw(
address indexed customerAddress,
uint256 indexed amountEthereum,
uint256 timestamp
);
event Referrer(
address indexed customerAddress,
address indexed referrer1,
address referrer2,
address referrer3,
address referrer4,
address referrer5,
uint256 timestamp
);
event Transfer(
address indexed from,
address indexed to,
uint tokens
);
event Approval(
address indexed tokenOwner,
address indexed spender,
uint tokens
);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) { return 0; }
uint256 c = a * b;
require(c / a == b, "Mul error");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "Div error");
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "Sub error");
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "Add error");
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Mod error");
return a % b;
}
} | *setGame() - the function of adding a new address of the game contract, from which you can receive dividends address gameAddress - the address of the game contract bool active - if TRUE, the dividends can be received/ | function setGame(address gameAddress, bool active) public onlyOwners returns(bool){
games[gameAddress] = active;
return true;
}
| 5,399,462 | [
1,
542,
12496,
1435,
300,
326,
445,
434,
6534,
279,
394,
1758,
434,
326,
7920,
6835,
16,
628,
1492,
1846,
848,
6798,
3739,
350,
5839,
1758,
7920,
1887,
300,
326,
1758,
434,
326,
7920,
6835,
1426,
2695,
300,
309,
5383,
16,
326,
3739,
350,
5839,
848,
506,
5079,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
12496,
12,
2867,
7920,
1887,
16,
1426,
2695,
13,
1071,
1338,
5460,
414,
1135,
12,
6430,
15329,
203,
3639,
28422,
63,
13957,
1887,
65,
273,
2695,
31,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.1;
pragma experimental ABIEncoderV2;
// import '@nomiclabs/buidler/console.sol';
import "./ERC1155.sol";
import "./IERC1155Views.sol";
contract TokensFlow is ERC1155, IERC1155Views {
using SafeMath for uint256;
using Address for address;
// See also _createSwapLimit()
struct SwapLimit {
bool recurring;
int256 initialSwapCredit;
int256 maxSwapCredit;
int swapCreditPeriod;
int firstTimeEnteredSwapCredit;
bytes32 hash;
}
struct TokenFlow {
uint256 parentToken;
SwapLimit limit;
int256 remainingSwapCredit;
int timeEnteredSwapCredit; // zero means not in a swap credit
int lastSwapTime; // ignored when not in a swap credit
bool enabled;
}
uint256 public maxTokenId;
mapping (uint256 => address) public tokenOwners;
mapping (uint256 => TokenFlow) public tokenFlow;
// IERC1155Views
mapping (uint256 => uint256) private totalSupplyImpl;
mapping (uint256 => string) private nameImpl;
mapping (uint256 => string) private symbolImpl;
mapping (uint256 => string) private uriImpl;
function totalSupply(uint256 _id) external override view returns (uint256) {
return totalSupplyImpl[_id];
}
function name(uint256 _id) external override view returns (string memory) {
return nameImpl[_id];
}
function symbol(uint256 _id) external override view returns (string memory) {
return symbolImpl[_id];
}
function decimals(uint256) external override pure returns (uint8) {
return 18;
}
function uri(uint256 _id) external override view returns (string memory) {
return uriImpl[_id];
}
// Administrativia
function newToken(uint256 _parent, string calldata _name, string calldata _symbol, string calldata _uri)
external returns (uint256)
{
return _newToken(_parent, _name, _symbol, _uri, msg.sender);
}
function setTokenOwner(uint256 _id, address _newOwner) external {
require(msg.sender == tokenOwners[_id]);
require(_id != 0);
tokenOwners[_id] = _newOwner;
}
function removeTokenOwner(uint256 _id) external {
require(msg.sender == tokenOwners[_id]);
tokenOwners[_id] = address(0);
}
// Intentially no setTokenName() and setTokenSymbol()
function setTokenUri(uint256 _id, string calldata _uri) external {
require(msg.sender == tokenOwners[_id]);
uriImpl[_id] = _uri;
}
// We don't check for circularities.
function setTokenParent(uint256 _child, uint256 _parent) external {
// require(_child != 0 && _child <= maxTokenId); // not needed
require(msg.sender == tokenOwners[_child]);
_setTokenParentNoCheck(_child, _parent);
}
// Each element of `_childs` list must be a child of the next one.
// TODO: Test. Especially test the case if the last child has no parent. Also test if a child is zero.
function setEnabled(uint256 _ancestor, uint256[] calldata _childs, bool _enabled) external {
require(msg.sender == tokenOwners[_ancestor]);
require(tokenFlow[_ancestor].enabled);
uint256 _firstChild = _childs[0]; // asserts on `_childs.length == 0`.
bool _hasRight = false; // if msg.sender is an ancestor
// Note that if in the below loops we disable ourselves, then it will be detected by a require
uint i = 0;
uint256 _parent;
for (uint256 _id = _firstChild; _id != 0; _id = _parent) {
_parent = tokenFlow[_id].parentToken;
if (i < _childs.length - 1) {
require(_parent == _childs[i + 1]);
}
if (_id == _ancestor) {
_hasRight = true;
break;
}
// We are not msg.sender
tokenFlow[_id].enabled = _enabled; // cannot enable for msg.sender
++i;
}
require(_hasRight);
}
// User can set negative values. It is a nonsense but does not harm.
function setRecurringFlow(
uint256 _child,
int256 _maxSwapCredit,
int256 _remainingSwapCredit,
int _swapCreditPeriod, int _timeEnteredSwapCredit,
bytes32 oldLimitHash) external
{
TokenFlow storage _flow = tokenFlow[_child];
require(msg.sender == tokenOwners[_flow.parentToken]);
require(_flow.limit.hash == oldLimitHash);
// require(_remainingSwapCredit <= _maxSwapCredit); // It is caller's responsibility.
_flow.limit = _createSwapLimit(true, _remainingSwapCredit, _maxSwapCredit, _swapCreditPeriod, _timeEnteredSwapCredit);
_flow.timeEnteredSwapCredit = _timeEnteredSwapCredit;
_flow.remainingSwapCredit = _remainingSwapCredit;
}
// User can set negative values. It is a nonsense but does not harm.
function setNonRecurringFlow(uint256 _child, int256 _remainingSwapCredit, bytes32 oldLimitHash) external {
TokenFlow storage _flow = tokenFlow[_child];
require(msg.sender == tokenOwners[_flow.parentToken]);
// require(_remainingSwapCredit <= _maxSwapCredit); // It is caller's responsibility.
require(_flow.limit.hash == oldLimitHash);
_flow.limit = _createSwapLimit(false, _remainingSwapCredit, 0, 0, 0);
_flow.remainingSwapCredit = _remainingSwapCredit;
}
// ERC-1155
// A token can anyway change its parent at any moment, so disabling of payments makes no sense.
// function safeTransferFrom(
// address _from,
// address _to,
// uint256 _id,
// uint256 _value,
// bytes calldata _data) external virtual override
// {
// require(tokenFlow[_id].enabled);
// super._safeTransferFrom(_from, _to, _id, _value, _data);
// }
// function safeBatchTransferFrom(
// address _from,
// address _to,
// uint256[] calldata _ids,
// uint256[] calldata _values,
// bytes calldata _data) external virtual override
// {
// for (uint i = 0; i < _ids.length; ++i) {
// require(tokenFlow[_ids[i]].enabled);
// }
// super._safeBatchTransferFrom(_from, _to, _ids, _values, _data);
// }
// Misc
function burn(address _from, uint256 _id, uint256 _value) external {
require(_from == msg.sender || operatorApproval[msg.sender][_from], "No approval.");
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
totalSupplyImpl[_id] -= _value; // no need to check overflow due to previous line
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
// Flow
// Each next token ID must be a parent of the previous one.
function exchangeToAncestor(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
// Intentionally no check for `msg.sender`.
require(_ids[_ids.length - 1] != 0); // The rest elements are checked below.
require(_amount < 1<<128);
uint256 _balance = balances[_ids[0]][msg.sender];
require(_amount <= _balance);
for(uint i = 0; i != _ids.length - 1; ++i) {
uint256 _id = _ids[i];
require(_id != 0);
uint256 _parent = tokenFlow[_id].parentToken;
require(_parent == _ids[i + 1]); // i ranges 0 .. _ids.length - 2
TokenFlow storage _flow = tokenFlow[_id];
require(_flow.enabled);
int _currentTimeResult = _currentTime();
uint256 _maxAllowedFlow;
bool _inSwapCreditResult;
if (_flow.limit.recurring) {
_inSwapCreditResult = _inSwapCredit(_flow, _currentTimeResult);
_maxAllowedFlow = _maxRecurringSwapAmount(_flow, _currentTimeResult, _inSwapCreditResult);
} else {
_maxAllowedFlow = _flow.remainingSwapCredit < 0 ? 0 : uint256(_flow.remainingSwapCredit);
}
require(_amount <= _maxAllowedFlow);
if (_flow.limit.recurring && !_inSwapCreditResult) {
_flow.timeEnteredSwapCredit = _currentTimeResult;
_flow.remainingSwapCredit = _flow.limit.maxSwapCredit;
}
_flow.lastSwapTime = _currentTimeResult; // TODO: no strictly necessary if !_flow.recurring
// require(_amount < 1<<128); // done above
_flow.remainingSwapCredit -= int256(_amount);
}
// if (_id == _flow.parentToken) return; // not necessary
_doBurn(msg.sender, _ids[0], _amount);
_doMint(msg.sender, _ids[_ids.length - 1], _amount, _data);
}
// Each next token ID must be a parent of the previous one.
function exchangeToDescendant(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
uint256 _parent = _ids[0];
require(_parent != 0);
for(uint i = 1; i != _ids.length; ++i) {
_parent = tokenFlow[_parent].parentToken;
require(_parent != 0);
require(_parent == _ids[i]); // consequently `_ids[i] != 0`
}
_doBurn(msg.sender, _ids[_ids.length - 1], _amount);
_doMint(msg.sender, _ids[0], _amount, _data);
}
// Internal
function _newToken(
uint256 _parent,
string memory _name, string memory _symbol, string memory _uri,
address _owner) internal returns (uint256)
{
tokenOwners[++maxTokenId] = _owner;
nameImpl[maxTokenId] = _name;
symbolImpl[maxTokenId] = _symbol;
uriImpl[maxTokenId] = _uri;
_setTokenParentNoCheck(maxTokenId, _parent);
emit NewToken(maxTokenId, _owner, _name, _symbol, _uri);
return maxTokenId;
}
function _doMint(address _to, uint256 _id, uint256 _value, bytes memory _data) public {
require(_to != address(0), "_to must be non-zero.");
if (_value != 0) {
totalSupplyImpl[_id] = _value.add(totalSupplyImpl[_id]);
balances[_id][_to] += _value; // no need to check for overflow due to the previous line
}
// MUST emit event
emit TransferSingle(msg.sender, address(0), _to, _id, _value);
// Now that the balance is updated and the event was emitted,
// call onERC1155Received if the destination is a contract.
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, address(0), _to, _id, _value, _data);
}
}
function _doBurn(address _from, uint256 _id, uint256 _value) public {
// require(_from != address(0), "_from must be non-zero.");
balances[_id][_from] = balances[_id][_from].sub(_value);
totalSupplyImpl[_id] -= _value; // no need to check for overflow due to the previous line
// MUST emit event
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
// Also resets swap credits and `enabled`, so use with caution.
// Allow this even if `!enabled` and set `enabled` to `true` if no parent,
// as otherwise impossible to enable it again.
function _setTokenParentNoCheck(uint256 _child, uint256 _parent) internal virtual {
require(_parent <= maxTokenId);
tokenFlow[_child] = TokenFlow({
parentToken: _parent,
limit: _createSwapLimit(false, 0, 0, 0, 0),
timeEnteredSwapCredit: 0, // zero means not in a swap credit
lastSwapTime: 0,
remainingSwapCredit: 0,
enabled: _parent == 0
});
}
function _currentTime() internal virtual view returns(int) {
return int(block.timestamp);
}
function _inSwapCredit(TokenFlow memory _flow, int _currentTimeResult) public pure returns(bool) {
// solhint-disable indent
return _flow.timeEnteredSwapCredit != 0 &&
_currentTimeResult - _flow.timeEnteredSwapCredit < _flow.limit.swapCreditPeriod;
}
function _maxRecurringSwapAmount(TokenFlow memory _flow, int _currentTimeResult, bool _inSwapCreditResult)
public pure returns(uint256)
{
int256 result;
if (_inSwapCreditResult) {
int256 passedTime = _currentTimeResult - _flow.lastSwapTime;
int256 delta = _flow.limit.maxSwapCredit * passedTime / _flow.limit.swapCreditPeriod;
result = _flow.remainingSwapCredit - delta;
} else {
result = _flow.limit.maxSwapCredit;
}
return result < 0 ? 0 : uint256(result);
}
function _createSwapLimit(
bool _recurring,
int256 _initialSwapCredit,
int256 _maxSwapCredit,
int _swapCreditPeriod,
int _firstTimeEnteredSwapCredit) pure internal returns (SwapLimit memory)
{
return SwapLimit({
recurring: _recurring,
initialSwapCredit: _initialSwapCredit,
maxSwapCredit: _maxSwapCredit,
swapCreditPeriod: _swapCreditPeriod,
firstTimeEnteredSwapCredit: _firstTimeEnteredSwapCredit,
hash: keccak256(abi.encodePacked(_recurring, _initialSwapCredit, _maxSwapCredit, _swapCreditPeriod, _firstTimeEnteredSwapCredit))
});
}
// Events
event NewToken(uint256 indexed id, address indexed owner, string name, string symbol, string uri);
}
| See also _createSwapLimit() | contract TokensFlow is ERC1155, IERC1155Views {
using SafeMath for uint256;
using Address for address;
pragma solidity ^0.7.1;
import "./ERC1155.sol";
struct SwapLimit {
bool recurring;
int256 initialSwapCredit;
int256 maxSwapCredit;
int swapCreditPeriod;
int firstTimeEnteredSwapCredit;
bytes32 hash;
}
struct TokenFlow {
uint256 parentToken;
SwapLimit limit;
int256 remainingSwapCredit;
bool enabled;
}
uint256 public maxTokenId;
mapping (uint256 => address) public tokenOwners;
mapping (uint256 => TokenFlow) public tokenFlow;
mapping (uint256 => uint256) private totalSupplyImpl;
mapping (uint256 => string) private nameImpl;
mapping (uint256 => string) private symbolImpl;
mapping (uint256 => string) private uriImpl;
function totalSupply(uint256 _id) external override view returns (uint256) {
return totalSupplyImpl[_id];
}
function name(uint256 _id) external override view returns (string memory) {
return nameImpl[_id];
}
function symbol(uint256 _id) external override view returns (string memory) {
return symbolImpl[_id];
}
function decimals(uint256) external override pure returns (uint8) {
return 18;
}
function uri(uint256 _id) external override view returns (string memory) {
return uriImpl[_id];
}
function newToken(uint256 _parent, string calldata _name, string calldata _symbol, string calldata _uri)
external returns (uint256)
{
return _newToken(_parent, _name, _symbol, _uri, msg.sender);
}
function setTokenOwner(uint256 _id, address _newOwner) external {
require(msg.sender == tokenOwners[_id]);
require(_id != 0);
tokenOwners[_id] = _newOwner;
}
function removeTokenOwner(uint256 _id) external {
require(msg.sender == tokenOwners[_id]);
tokenOwners[_id] = address(0);
}
function setTokenUri(uint256 _id, string calldata _uri) external {
require(msg.sender == tokenOwners[_id]);
uriImpl[_id] = _uri;
}
function setTokenParent(uint256 _child, uint256 _parent) external {
require(msg.sender == tokenOwners[_child]);
_setTokenParentNoCheck(_child, _parent);
}
function setEnabled(uint256 _ancestor, uint256[] calldata _childs, bool _enabled) external {
require(msg.sender == tokenOwners[_ancestor]);
require(tokenFlow[_ancestor].enabled);
uint i = 0;
uint256 _parent;
for (uint256 _id = _firstChild; _id != 0; _id = _parent) {
_parent = tokenFlow[_id].parentToken;
if (i < _childs.length - 1) {
require(_parent == _childs[i + 1]);
}
if (_id == _ancestor) {
_hasRight = true;
break;
}
}
require(_hasRight);
}
function setEnabled(uint256 _ancestor, uint256[] calldata _childs, bool _enabled) external {
require(msg.sender == tokenOwners[_ancestor]);
require(tokenFlow[_ancestor].enabled);
uint i = 0;
uint256 _parent;
for (uint256 _id = _firstChild; _id != 0; _id = _parent) {
_parent = tokenFlow[_id].parentToken;
if (i < _childs.length - 1) {
require(_parent == _childs[i + 1]);
}
if (_id == _ancestor) {
_hasRight = true;
break;
}
}
require(_hasRight);
}
function setEnabled(uint256 _ancestor, uint256[] calldata _childs, bool _enabled) external {
require(msg.sender == tokenOwners[_ancestor]);
require(tokenFlow[_ancestor].enabled);
uint i = 0;
uint256 _parent;
for (uint256 _id = _firstChild; _id != 0; _id = _parent) {
_parent = tokenFlow[_id].parentToken;
if (i < _childs.length - 1) {
require(_parent == _childs[i + 1]);
}
if (_id == _ancestor) {
_hasRight = true;
break;
}
}
require(_hasRight);
}
function setEnabled(uint256 _ancestor, uint256[] calldata _childs, bool _enabled) external {
require(msg.sender == tokenOwners[_ancestor]);
require(tokenFlow[_ancestor].enabled);
uint i = 0;
uint256 _parent;
for (uint256 _id = _firstChild; _id != 0; _id = _parent) {
_parent = tokenFlow[_id].parentToken;
if (i < _childs.length - 1) {
require(_parent == _childs[i + 1]);
}
if (_id == _ancestor) {
_hasRight = true;
break;
}
}
require(_hasRight);
}
++i;
function setRecurringFlow(
uint256 _child,
int256 _maxSwapCredit,
int256 _remainingSwapCredit,
int _swapCreditPeriod, int _timeEnteredSwapCredit,
bytes32 oldLimitHash) external
{
TokenFlow storage _flow = tokenFlow[_child];
require(msg.sender == tokenOwners[_flow.parentToken]);
require(_flow.limit.hash == oldLimitHash);
_flow.limit = _createSwapLimit(true, _remainingSwapCredit, _maxSwapCredit, _swapCreditPeriod, _timeEnteredSwapCredit);
_flow.timeEnteredSwapCredit = _timeEnteredSwapCredit;
_flow.remainingSwapCredit = _remainingSwapCredit;
}
function setNonRecurringFlow(uint256 _child, int256 _remainingSwapCredit, bytes32 oldLimitHash) external {
TokenFlow storage _flow = tokenFlow[_child];
require(msg.sender == tokenOwners[_flow.parentToken]);
require(_flow.limit.hash == oldLimitHash);
_flow.limit = _createSwapLimit(false, _remainingSwapCredit, 0, 0, 0);
_flow.remainingSwapCredit = _remainingSwapCredit;
}
function burn(address _from, uint256 _id, uint256 _value) external {
require(_from == msg.sender || operatorApproval[msg.sender][_from], "No approval.");
balances[_id][_from] = balances[_id][_from].sub(_value);
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
function exchangeToAncestor(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
require(_amount < 1<<128);
uint256 _balance = balances[_ids[0]][msg.sender];
require(_amount <= _balance);
for(uint i = 0; i != _ids.length - 1; ++i) {
uint256 _id = _ids[i];
require(_id != 0);
uint256 _parent = tokenFlow[_id].parentToken;
TokenFlow storage _flow = tokenFlow[_id];
require(_flow.enabled);
int _currentTimeResult = _currentTime();
uint256 _maxAllowedFlow;
bool _inSwapCreditResult;
if (_flow.limit.recurring) {
_inSwapCreditResult = _inSwapCredit(_flow, _currentTimeResult);
_maxAllowedFlow = _maxRecurringSwapAmount(_flow, _currentTimeResult, _inSwapCreditResult);
_maxAllowedFlow = _flow.remainingSwapCredit < 0 ? 0 : uint256(_flow.remainingSwapCredit);
}
require(_amount <= _maxAllowedFlow);
if (_flow.limit.recurring && !_inSwapCreditResult) {
_flow.timeEnteredSwapCredit = _currentTimeResult;
_flow.remainingSwapCredit = _flow.limit.maxSwapCredit;
}
}
_doMint(msg.sender, _ids[_ids.length - 1], _amount, _data);
}
function exchangeToAncestor(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
require(_amount < 1<<128);
uint256 _balance = balances[_ids[0]][msg.sender];
require(_amount <= _balance);
for(uint i = 0; i != _ids.length - 1; ++i) {
uint256 _id = _ids[i];
require(_id != 0);
uint256 _parent = tokenFlow[_id].parentToken;
TokenFlow storage _flow = tokenFlow[_id];
require(_flow.enabled);
int _currentTimeResult = _currentTime();
uint256 _maxAllowedFlow;
bool _inSwapCreditResult;
if (_flow.limit.recurring) {
_inSwapCreditResult = _inSwapCredit(_flow, _currentTimeResult);
_maxAllowedFlow = _maxRecurringSwapAmount(_flow, _currentTimeResult, _inSwapCreditResult);
_maxAllowedFlow = _flow.remainingSwapCredit < 0 ? 0 : uint256(_flow.remainingSwapCredit);
}
require(_amount <= _maxAllowedFlow);
if (_flow.limit.recurring && !_inSwapCreditResult) {
_flow.timeEnteredSwapCredit = _currentTimeResult;
_flow.remainingSwapCredit = _flow.limit.maxSwapCredit;
}
}
_doMint(msg.sender, _ids[_ids.length - 1], _amount, _data);
}
function exchangeToAncestor(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
require(_amount < 1<<128);
uint256 _balance = balances[_ids[0]][msg.sender];
require(_amount <= _balance);
for(uint i = 0; i != _ids.length - 1; ++i) {
uint256 _id = _ids[i];
require(_id != 0);
uint256 _parent = tokenFlow[_id].parentToken;
TokenFlow storage _flow = tokenFlow[_id];
require(_flow.enabled);
int _currentTimeResult = _currentTime();
uint256 _maxAllowedFlow;
bool _inSwapCreditResult;
if (_flow.limit.recurring) {
_inSwapCreditResult = _inSwapCredit(_flow, _currentTimeResult);
_maxAllowedFlow = _maxRecurringSwapAmount(_flow, _currentTimeResult, _inSwapCreditResult);
_maxAllowedFlow = _flow.remainingSwapCredit < 0 ? 0 : uint256(_flow.remainingSwapCredit);
}
require(_amount <= _maxAllowedFlow);
if (_flow.limit.recurring && !_inSwapCreditResult) {
_flow.timeEnteredSwapCredit = _currentTimeResult;
_flow.remainingSwapCredit = _flow.limit.maxSwapCredit;
}
}
_doMint(msg.sender, _ids[_ids.length - 1], _amount, _data);
}
} else {
function exchangeToAncestor(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
require(_amount < 1<<128);
uint256 _balance = balances[_ids[0]][msg.sender];
require(_amount <= _balance);
for(uint i = 0; i != _ids.length - 1; ++i) {
uint256 _id = _ids[i];
require(_id != 0);
uint256 _parent = tokenFlow[_id].parentToken;
TokenFlow storage _flow = tokenFlow[_id];
require(_flow.enabled);
int _currentTimeResult = _currentTime();
uint256 _maxAllowedFlow;
bool _inSwapCreditResult;
if (_flow.limit.recurring) {
_inSwapCreditResult = _inSwapCredit(_flow, _currentTimeResult);
_maxAllowedFlow = _maxRecurringSwapAmount(_flow, _currentTimeResult, _inSwapCreditResult);
_maxAllowedFlow = _flow.remainingSwapCredit < 0 ? 0 : uint256(_flow.remainingSwapCredit);
}
require(_amount <= _maxAllowedFlow);
if (_flow.limit.recurring && !_inSwapCreditResult) {
_flow.timeEnteredSwapCredit = _currentTimeResult;
_flow.remainingSwapCredit = _flow.limit.maxSwapCredit;
}
}
_doMint(msg.sender, _ids[_ids.length - 1], _amount, _data);
}
_flow.remainingSwapCredit -= int256(_amount);
_doBurn(msg.sender, _ids[0], _amount);
function exchangeToDescendant(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
uint256 _parent = _ids[0];
require(_parent != 0);
for(uint i = 1; i != _ids.length; ++i) {
_parent = tokenFlow[_parent].parentToken;
require(_parent != 0);
}
_doBurn(msg.sender, _ids[_ids.length - 1], _amount);
_doMint(msg.sender, _ids[0], _amount, _data);
}
function exchangeToDescendant(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
uint256 _parent = _ids[0];
require(_parent != 0);
for(uint i = 1; i != _ids.length; ++i) {
_parent = tokenFlow[_parent].parentToken;
require(_parent != 0);
}
_doBurn(msg.sender, _ids[_ids.length - 1], _amount);
_doMint(msg.sender, _ids[0], _amount, _data);
}
function _newToken(
uint256 _parent,
string memory _name, string memory _symbol, string memory _uri,
address _owner) internal returns (uint256)
{
tokenOwners[++maxTokenId] = _owner;
nameImpl[maxTokenId] = _name;
symbolImpl[maxTokenId] = _symbol;
uriImpl[maxTokenId] = _uri;
_setTokenParentNoCheck(maxTokenId, _parent);
emit NewToken(maxTokenId, _owner, _name, _symbol, _uri);
return maxTokenId;
}
function _doMint(address _to, uint256 _id, uint256 _value, bytes memory _data) public {
require(_to != address(0), "_to must be non-zero.");
if (_value != 0) {
totalSupplyImpl[_id] = _value.add(totalSupplyImpl[_id]);
}
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, address(0), _to, _id, _value, _data);
}
}
function _doMint(address _to, uint256 _id, uint256 _value, bytes memory _data) public {
require(_to != address(0), "_to must be non-zero.");
if (_value != 0) {
totalSupplyImpl[_id] = _value.add(totalSupplyImpl[_id]);
}
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, address(0), _to, _id, _value, _data);
}
}
emit TransferSingle(msg.sender, address(0), _to, _id, _value);
function _doMint(address _to, uint256 _id, uint256 _value, bytes memory _data) public {
require(_to != address(0), "_to must be non-zero.");
if (_value != 0) {
totalSupplyImpl[_id] = _value.add(totalSupplyImpl[_id]);
}
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, address(0), _to, _id, _value, _data);
}
}
function _doBurn(address _from, uint256 _id, uint256 _value) public {
balances[_id][_from] = balances[_id][_from].sub(_value);
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
function _setTokenParentNoCheck(uint256 _child, uint256 _parent) internal virtual {
require(_parent <= maxTokenId);
tokenFlow[_child] = TokenFlow({
parentToken: _parent,
limit: _createSwapLimit(false, 0, 0, 0, 0),
lastSwapTime: 0,
remainingSwapCredit: 0,
enabled: _parent == 0
});
}
function _setTokenParentNoCheck(uint256 _child, uint256 _parent) internal virtual {
require(_parent <= maxTokenId);
tokenFlow[_child] = TokenFlow({
parentToken: _parent,
limit: _createSwapLimit(false, 0, 0, 0, 0),
lastSwapTime: 0,
remainingSwapCredit: 0,
enabled: _parent == 0
});
}
function _currentTime() internal virtual view returns(int) {
return int(block.timestamp);
}
function _inSwapCredit(TokenFlow memory _flow, int _currentTimeResult) public pure returns(bool) {
return _flow.timeEnteredSwapCredit != 0 &&
_currentTimeResult - _flow.timeEnteredSwapCredit < _flow.limit.swapCreditPeriod;
}
function _maxRecurringSwapAmount(TokenFlow memory _flow, int _currentTimeResult, bool _inSwapCreditResult)
public pure returns(uint256)
{
int256 result;
if (_inSwapCreditResult) {
int256 passedTime = _currentTimeResult - _flow.lastSwapTime;
int256 delta = _flow.limit.maxSwapCredit * passedTime / _flow.limit.swapCreditPeriod;
result = _flow.remainingSwapCredit - delta;
result = _flow.limit.maxSwapCredit;
}
return result < 0 ? 0 : uint256(result);
}
function _maxRecurringSwapAmount(TokenFlow memory _flow, int _currentTimeResult, bool _inSwapCreditResult)
public pure returns(uint256)
{
int256 result;
if (_inSwapCreditResult) {
int256 passedTime = _currentTimeResult - _flow.lastSwapTime;
int256 delta = _flow.limit.maxSwapCredit * passedTime / _flow.limit.swapCreditPeriod;
result = _flow.remainingSwapCredit - delta;
result = _flow.limit.maxSwapCredit;
}
return result < 0 ? 0 : uint256(result);
}
} else {
function _createSwapLimit(
bool _recurring,
int256 _initialSwapCredit,
int256 _maxSwapCredit,
int _swapCreditPeriod,
int _firstTimeEnteredSwapCredit) pure internal returns (SwapLimit memory)
{
return SwapLimit({
recurring: _recurring,
initialSwapCredit: _initialSwapCredit,
maxSwapCredit: _maxSwapCredit,
swapCreditPeriod: _swapCreditPeriod,
firstTimeEnteredSwapCredit: _firstTimeEnteredSwapCredit,
hash: keccak256(abi.encodePacked(_recurring, _initialSwapCredit, _maxSwapCredit, _swapCreditPeriod, _firstTimeEnteredSwapCredit))
});
}
event NewToken(uint256 indexed id, address indexed owner, string name, string symbol, string uri);
function _createSwapLimit(
bool _recurring,
int256 _initialSwapCredit,
int256 _maxSwapCredit,
int _swapCreditPeriod,
int _firstTimeEnteredSwapCredit) pure internal returns (SwapLimit memory)
{
return SwapLimit({
recurring: _recurring,
initialSwapCredit: _initialSwapCredit,
maxSwapCredit: _maxSwapCredit,
swapCreditPeriod: _swapCreditPeriod,
firstTimeEnteredSwapCredit: _firstTimeEnteredSwapCredit,
hash: keccak256(abi.encodePacked(_recurring, _initialSwapCredit, _maxSwapCredit, _swapCreditPeriod, _firstTimeEnteredSwapCredit))
});
}
event NewToken(uint256 indexed id, address indexed owner, string name, string symbol, string uri);
}
| 1,073,089 | [
1,
9704,
2546,
389,
2640,
12521,
3039,
1435,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
13899,
5249,
353,
4232,
39,
2499,
2539,
16,
467,
654,
39,
2499,
2539,
9959,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
27,
18,
21,
31,
203,
5666,
25165,
654,
39,
2499,
2539,
18,
18281,
14432,
203,
565,
1958,
12738,
3039,
288,
203,
3639,
1426,
26043,
31,
203,
3639,
509,
5034,
2172,
12521,
16520,
31,
203,
3639,
509,
5034,
943,
12521,
16520,
31,
203,
3639,
509,
7720,
16520,
5027,
31,
203,
3639,
509,
1122,
950,
10237,
329,
12521,
16520,
31,
203,
3639,
1731,
1578,
1651,
31,
203,
565,
289,
203,
203,
565,
1958,
3155,
5249,
288,
203,
3639,
2254,
5034,
982,
1345,
31,
203,
3639,
12738,
3039,
1800,
31,
203,
3639,
509,
5034,
4463,
12521,
16520,
31,
203,
3639,
1426,
3696,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
1071,
943,
1345,
548,
31,
203,
203,
565,
2874,
261,
11890,
5034,
516,
1758,
13,
1071,
1147,
5460,
414,
31,
203,
203,
565,
2874,
261,
11890,
5034,
516,
3155,
5249,
13,
1071,
1147,
5249,
31,
203,
203,
565,
2874,
261,
11890,
5034,
516,
2254,
5034,
13,
3238,
2078,
3088,
1283,
2828,
31,
203,
565,
2874,
261,
11890,
5034,
516,
533,
13,
3238,
508,
2828,
31,
203,
565,
2874,
261,
11890,
5034,
516,
533,
13,
3238,
3273,
2828,
31,
203,
565,
2874,
261,
11890,
5034,
516,
533,
13,
3238,
2003,
2828,
31,
203,
203,
203,
565,
445,
2078,
3088,
1283,
12,
11890,
5034,
389,
350,
13,
2
] |
./full_match/1/0xc5FCC5139eDeD36c31B7EEE0E9A57ac8DAF4E42a/sources/fubu.sol | Set the amount of blocks to count a sniper. DxLocker Address (BSC) Approve the owner for PancakeSwap, timesaver. Ever-growing sniper/tool blacklist | constructor (uint256 _snipeBlockAmt, uint256 _gasPriceLimit) payable {
_tOwned[_msgSender()] = _tTotal;
_rOwned[_msgSender()] = _rTotal;
snipeBlockAmt = _snipeBlockAmt;
gasPriceLimit = _gasPriceLimit * 1 gwei;
IUniswapV2Router02 _dexRouter = IUniswapV2Router02(_routerAddress);
lpPair = IUniswapV2Factory(_dexRouter.factory())
.createPair(address(this), _dexRouter.WETH());
dexRouter = _dexRouter;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_liquidityHolders[owner()] = true;
_isExcluded[address(this)] = true;
_excluded.push(address(this));
_isExcluded[owner()] = true;
_excluded.push(owner());
_isExcluded[burnAddress] = true;
_excluded.push(burnAddress);
_isExcluded[_marketingWallet] = true;
_excluded.push(_marketingWallet);
_isExcluded[lpPair] = true;
_excluded.push(lpPair);
_isExcludedFromFee[0x2D045410f002A95EFcEE67759A92518fA3FcE677] = true;
_isExcluded[0x2D045410f002A95EFcEE67759A92518fA3FcE677] = true;
_excluded.push(0x2D045410f002A95EFcEE67759A92518fA3FcE677);
_approve(_msgSender(), _routerAddress, _tTotal);
emit Transfer(address(0), _msgSender(), _tTotal);
}
| 3,850,589 | [
1,
694,
326,
3844,
434,
4398,
358,
1056,
279,
4556,
77,
457,
18,
463,
92,
2531,
264,
5267,
261,
38,
2312,
13,
1716,
685,
537,
326,
3410,
364,
12913,
23780,
12521,
16,
4124,
21851,
18,
512,
502,
17,
75,
492,
310,
4556,
77,
457,
19,
6738,
11709,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
261,
11890,
5034,
389,
8134,
3151,
1768,
31787,
16,
2254,
5034,
389,
31604,
5147,
3039,
13,
8843,
429,
288,
203,
3639,
389,
88,
5460,
329,
63,
67,
3576,
12021,
1435,
65,
273,
389,
88,
5269,
31,
203,
3639,
389,
86,
5460,
329,
63,
67,
3576,
12021,
1435,
65,
273,
389,
86,
5269,
31,
203,
203,
3639,
4556,
3151,
1768,
31787,
273,
389,
8134,
3151,
1768,
31787,
31,
203,
3639,
16189,
5147,
3039,
273,
389,
31604,
5147,
3039,
380,
404,
314,
1814,
77,
31,
203,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
561,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
24899,
10717,
1887,
1769,
203,
3639,
12423,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
561,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
561,
8259,
18,
59,
1584,
44,
10663,
203,
203,
3639,
302,
338,
8259,
273,
389,
561,
8259,
31,
203,
540,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
3639,
389,
549,
372,
24237,
27003,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
3639,
389,
24602,
18,
6206,
12,
2867,
12,
2211,
10019,
203,
3639,
389,
291,
16461,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
24602,
18,
6206,
12,
8443,
10663,
203,
3639,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/presets/ERC20PresetMinterPauserUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
/**
* @dev ERC20 token with minting, burning and pausable token transfers.
*
*/
contract EnhancedMinterPauser is
Initializable,
ERC20PresetMinterPauserUpgradeable,
OwnableUpgradeable
{
using SafeMathUpgradeable for uint256;
//role for excluding addresses for feeless transfer
bytes32 public constant FEE_EXCLUDED_ROLE = keccak256("FEE_EXCLUDED_ROLE");
// fee percent represented in integer for example 400, will be used as 1/400 = 0,0025 percent
uint32 public tokenTransferFeeDivisor;
//address where the transfer fees will be sent
address public feeAddress;
event feeWalletAddressChanged(address newValue);
event mintingFeePercentChanged(uint32 newValue);
function __EnhancedMinterPauser_init(
string memory name,
string memory symbol
) internal initializer {
__ERC20_init_unchained(name, symbol);
__ERC20PresetMinterPauser_init_unchained(name, symbol);
__EnhancedMinterPauser_init_unchained();
__Ownable_init();
}
function __EnhancedMinterPauser_init_unchained() internal initializer {
_setupRole(FEE_EXCLUDED_ROLE, _msgSender());
setFeeWalletAddress(0x9D1Cb8509A7b60421aB28492ce05e06f52Ddf727);
setTransferFeeDivisor(400);
}
/**
* @dev minting without 18 decimal places for convenience
* if withFee = true calls the mintWithFee function
* else sends the minted tokens without substracting a fee
*/
function mintWithoutDecimals(
address recipient,
uint256 amount,
bool withFee
) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to mint"
);
if (withFee) {
mintWithFee(recipient, amount * 1 ether);
} else super._mint(recipient, amount * 1 ether);
}
/**
* @dev mint tokens substract the fee, send the fee to the fee wallet
* and send the final amount to the given address
*/
function mintWithFee(address recipient, uint256 amount) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to mint"
);
//transfer fee
super._mint(feeAddress, _calculateFee(amount));
super._mint(recipient, _calculateAmountSubTransferFee(amount));
}
/**
* @dev overriding the openzeppelin _transfer method
* if the sender address is not excluded substract transfer fee from the amount
* and send the fee to the predefined fee address
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
if (hasRole(FEE_EXCLUDED_ROLE, _msgSender())) {
super._transfer(
sender,
recipient,
amount
);
} else {
// transfer amount - fee
super._transfer(
sender,
recipient,
_calculateAmountSubTransferFee(amount)
);
//transfer the fee to the predefined fee address
super._transfer(sender, feeAddress, _calculateFee(amount));
}
}
/**
* @dev set the wallet address where fees will be collected
*/
function setFeeWalletAddress(address _feeAddress) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to set minting fee address"
);
require(address(0) != address(_feeAddress),
"zero address is not allowed"
);
feeAddress = _feeAddress;
emit feeWalletAddressChanged(feeAddress);
}
/**
* @dev sets the transfer fee
* example: divisor 400 would equal to 0,05 percent; 1/400 = 0,0025/100
*/
function setTransferFeeDivisor(uint32 _tokenTransferFeeDivisor) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to set minting fee percent"
);
require(
_tokenTransferFeeDivisor > 2,
"Token transfer fee divisor must be greater than 0"
);
tokenTransferFeeDivisor = _tokenTransferFeeDivisor;
emit mintingFeePercentChanged(tokenTransferFeeDivisor);
}
/**
* @dev calculates the total amount minus the the transfer fee
*/
function _calculateAmountSubTransferFee(uint256 amount)
private
view
returns (uint256)
{
return amount.sub(_calculateFee(amount));
}
/**
* @dev calculates the transfer fee
*/
function _calculateFee(uint256 amount) private view returns (uint256) {
return amount.div(tokenTransferFeeDivisor);
}
uint256[50] private __gap;
}
| * @dev calculates the transfer fee/ | function _calculateFee(uint256 amount) private view returns (uint256) {
return amount.div(tokenTransferFeeDivisor);
}
uint256[50] private __gap;
| 12,573,243 | [
1,
12780,
815,
326,
7412,
14036,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
11162,
14667,
12,
11890,
5034,
3844,
13,
3238,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
3844,
18,
2892,
12,
2316,
5912,
14667,
7244,
12385,
1769,
203,
565,
289,
203,
203,
565,
2254,
5034,
63,
3361,
65,
3238,
1001,
14048,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x3A70F276Ba72A7a7810b07b6349d0a9cA515200f/sources/localhost/MONA/03-Presale/MONA__Presale.sol | address where liquidity pool tokens will be locked | constructor(IERC20 _token, address _liquidityLockAddress ) {
token = _token;
owner = msg.sender;
liquidityLockAddress = _liquidityLockAddress;
monatoken = MonaToken( address( _token ) );
uniswapFactory = UniswapV2Factory( uniswapFactoryAddress );
uniswapRouter = UniswapV2Router02( uniswapRouterAddress );
if( uniswapPair == address(0) ){
uniswapPair = uniswapFactory.createPair(
address( uniswapRouter.WETH() ),
address( token )
);
}
whitelistaddress[0x75B0bBD46d7752CB2f5FfE645467e0ce6E389795] = true;
whitelistaddress[0xA43c750d5dE3Bd88EE4F35DEF72Cf76afEbeC274] = true;
whitelistaddress[0xE5a7Efe11e3f237fDD9b0ebe1a7d7F1380f5f710] = true;
whitelistaddress[0x42147EE918238fdfF257a15fA758944D6b870B6A] = true;
whitelistaddress[0x5b049c3Bef543a181A720DcC6fEbc9afdab5D377] = true;
whitelistaddress[0xa8A7C1E6BddD585995368F3E6bF273b157671f9E] = true;
whitelistaddress[0x69Bb92BF0641Df61783EA18c01f96656424bD76C] = true;
whitelistaddress[0xCFFC9c89C666456819B9cdd4549cc04168986AcE] = true;
whitelistaddress[0x8e47cD04F8D64E6Dd0b9847F65923Dc0141EF8a6] = true;
whitelistaddress[0x8fd3a93633DCA8763EAe1f0e50b8961101Dc07e5] = true;
whitelistaddress[0xD895689d4e6390bFd43AeEff844bC8C98E76F7cD] = true;
whitelistaddress[0x710049Cfe15475b24D587CC2bF5fFa2007E7a9BE] = true;
whitelistaddress[0x063419424C685C76c0a77d32391B487DF398210f] = true;
whitelistaddress[0x1d3ab981AC3ab27B35e4aBaAA0a4de1C48b04C52] = true;
whitelistaddress[0xcA7F8f6A21C6e0F3b0177207407Fc935429BdD27] = true;
whitelistaddress[0xF5233A9cB0a3F3d611003f7B7ceC383F2621D5d8] = true;
whitelistaddress[0xcD1dF5D0f679D15dc3125aE515a7D01abe67A59d] = true;
whitelistaddress[0xC0B374f27abcCD5f34e30bA437AdF10f084a66c4] = true;
whitelistaddress[0x1972Ee26aF7A279d805844215F0fE55008431430] = true;
whitelistaddress[0xc8b73257B1AE9F5f29b6049bFd2FFf3696C6372e] = true;
whitelistaddress[0xeaaE817e2BFd572a58dD5c3e700a7A5bA4e51141] = true;
whitelistaddress[0xd838a891E891d9E59942a5d04d26B1b67a0e6779] = true;
whitelistaddress[0x12B6B076B169ca1d25B7aC5Dec436EA8067b0CF6] = true;
whitelistaddress[0x548efCE69bb82a16f3911a86a65384327c99c3Ab] = true;
whitelistaddress[0x34d4ECD77D6378EbddA1C62A38881E4587109181] = true;
whitelistaddress[0x5E8ac6c5C190bFfb0492D01018DcB98C79C8d830] = true;
whitelistaddress[0x166B6770f7513ee4BE7a88f7C8d250E5E8BCbfAF] = true;
whitelistaddress[0x9Cd22A6396A1335834A616A151a63538886F4356] = true;
whitelistaddress[0xc31440748bC461217E19EdA76aaf8145Bf9a45BD] = true;
whitelistaddress[0xb80A3488Bd3f1c5A2D6Fce9B095707ec62172Fb5] = true;
whitelistaddress[0xcbBC5D06BE48B9B1D90A8E787B4d42bc4A3B74a8] = true;
whitelistaddress[0xB1ab255D5E2C1C2fbEbE3596629a513ba9EE57A3] = true;
whitelistaddress[0x39b6b54A164fE3c7D6f315ec737bD896670b4B3c] = true;
whitelistaddress[0x92156573daC216BE021A1A4F467121be92991D73] = true;
whitelistaddress[0x11606a9336651aFdB20580B4043b740CDa9352Bd] = true;
whitelistaddress[0xdC38A69fFDB6f4F9eE44cb4E9a8dE20556Be3fB0] = true;
whitelistaddress[0xab98eefc9958A22C6f5D8B0891fB4178f1e27878] = true;
whitelistaddress[0xdec08cb92a506B88411da9Ba290f3694BE223c26] = true;
whitelistaddress[0x0eC5eFdE04e88a1226a31cC942051056aF78AfEB] = true;
whitelistaddress[0x04b936745C02E8Cb75cC68b93B4fb99b38939d5D] = true;
whitelistaddress[0x867a3Acf77ca8a20734473D3df9A3b0fafE543fc] = true;
whitelistaddress[0x7724446d415a32e3bC21808156b1C379fd995248] = true;
whitelistaddress[0x8Bf97E5a744419b0cFfA0e026eef06Decd3bE9d0] = true;
whitelistaddress[0x2Bbf0BD417e11b36599338A5a23aA22269c2Dc0D] = true;
whitelistaddress[0x751C2D211ecE742Ec2C911BEE70c4A6eD7708915] = true;
whitelistaddress[0x9FE11FeBb44aeFFf4c2f855b19424518Bdf73Fce] = true;
whitelistaddress[0x032272075923eecbdF5C897Ce390821C97f923Ae] = true;
whitelistaddress[0xbD7d7cD3FB9Be282181e5fd4ed9D47819133a867] = true;
whitelistaddress[0xDB4b807DdcF7b263C183aD6e486E6a3AcC9d76A5] = true;
whitelistaddress[0xcBf75675F86917ed9536D60FD26E65f83D58c26b] = true;
whitelistaddress[0x89A5d9e66AA6439f9daBa379078193AbA58d949a] = true;
whitelistaddress[0xc8845aD3ffd878f6c3f302DE73c40d92dDc8f709] = true;
whitelistaddress[0xDF01CCb3Ee32C0970141C048c3bD95bcdccD5c70] = true;
whitelistaddress[0x0d79cce030AE9654aA9488524F407ce464297722] = true;
whitelistaddress[0xaaEDD6eD3c301D3985d5eDD4F0E548d69d94dBe3] = true;
whitelistaddress[0x132b0065386A4B750160573f618F3F657A8a370f] = true;
whitelistaddress[0xF6196741d0896dc362788C1FDbDF91b544Ab7C1C] = true;
whitelistaddress[0xeFedba0B7330F83e9A46AfBF52321c9329c74df1] = true;
whitelistaddress[0xEde59a36Dc09BC96D00381fBf1FD66B21aadcF73] = true;
whitelistaddress[0xa594Cd4b249cad1eFC7ff43622a1E950838c458b] = true;
whitelistaddress[0xff37697171B95605b4511030C9Cdc2dcEA0A51e2] = true;
whitelistaddress[0x8510cc4729Ec86bA82405e3A0AfBde52C9676E2b] = true;
whitelistaddress[0xf63370F0a9C09d53e1A410181BD80831934EfB19] = true;
whitelistaddress[0x2f17AC34a6685DafF6E711190986E11957762Ebc] = true;
whitelistaddress[0x33Ff94D466183CC462B02bAD19374a434bA2C072] = true;
whitelistaddress[0x459B3EDb577cB0b25C6c9ae94510900b4a008931] = true;
whitelistaddress[0x92048DB9D572F3D153d415A41502aD20e9756904] = true;
whitelistaddress[0x4Bb7bF6C79c8D90B7e26f73ff27869eeF934351e] = true;
whitelistaddress[0x93f5af632Ce523286e033f0510E9b3C9710F4489] = true;
whitelistaddress[0x1e5A689F9D4524Ff6f604cDA19c01FAa4cA664eA] = true;
whitelistaddress[0x47262B32A23B902A5083B3be5e6A270A71bE83E0] = true;
whitelistaddress[0xd1883a30F95b7489D3922a8069725631C5474aAB] = true;
whitelistaddress[0x407E5C8a607A5f3B7d3b4ffa1C51D965d9b13083] = true;
whitelistaddress[0x3471884f189FD7C63fe8C83601D28cE0Cc1B3853] = true;
whitelistaddress[0x184906f076ACB00E9D14fe10607F3A187347f18F] = true;
whitelistaddress[0x8d9f46510152be0147FA8b2C92eec099e42EA66c] = true;
whitelistaddress[0x9B269141E3B2924E4Fec66351607981638c0F30F] = true;
whitelistaddress[0xcDeF7D2119f61f3cA94359EBbC49B1C19efbd384] = true;
whitelistaddress[0x7B0D7d53dFC6dCa1563674759D965896abB7cfe1] = true;
whitelistaddress[0x5E7aaEad11e3413E9d891A3A9c34B15552C879bF] = true;
whitelistaddress[0x84998f375355AE7AE7f60e8ecF1D24ad59948e9a] = true;
whitelistaddress[0xD9657748776cF40B42E4C11fDC78c1337555F0E3] = true;
whitelistaddress[0x8eF8A98402CD37d4bF759319CA3D05eC99B2A4e9] = true;
whitelistaddress[0x00A1A5f529975d5ba9A579e5C683243Bccd42E4a] = true;
whitelistaddress[0xAcEcE2C109AF6fDA78125cDa83c40E04dafEe10d] = true;
whitelistaddress[0x06da20fF018e3Dc3cFA9ea16f687bf3b22668914] = true;
whitelistaddress[0xF29680cFb7893CF142C603580604D748A7De6e65] = true;
whitelistaddress[0x81d399f7564c255389c6863e34B351Ff8bBAe1B6] = true;
whitelistaddress[0x40feBfC8cC40712937021d117a5fD299C44DD09D] = true;
whitelistaddress[0xC6CDf738242710c1A7d9a28aC30b89453ffc823F] = true;
whitelistaddress[0xb7fc44237eE35D7b533037cbA2298E54c3d59276] = true;
whitelistaddress[0xb663c144779a80A8E24D3E8c39E774549eB84057] = true;
whitelistaddress[0x740546fABff217A472b02EBaa689155AaA5f0CC6] = true;
whitelistaddress[0x04E3602639475A67E453FB6Ae37816Da02E50c1E] = true;
whitelistaddress[0x9AEC07A9c0417FcE4318e5C18ED12783Ff7b0FD4] = true;
whitelistaddress[0x590dfbD53781c6d9D8404eB8e1847fEA1AfAD319] = true;
whitelistaddress[0xCbaFAE637587e048cAd5B2f9736996A76308D99E] = true;
whitelistaddress[0xCA9b022976AdfD4d6eE7BF97be6FeE8689D45cf1] = true;
whitelistaddress[0xDA9f6e5748c13BF79eAab5BBc515334D16d9b7E2] = true;
whitelistaddress[0xD6dBed6297B539A11f1aAb7907e7DF7d9FFeda7e] = true;
whitelistaddress[0x9A8ea427c5CF4490c07428b853A5577c9B7a2d14] = true;
whitelistaddress[0xa364b412570Ec8013cAcC63c1096620aeDAC0C48] = true;
whitelistaddress[0x6C71839Cc2067cCC3E492b2372e41d0343328931] = true;
whitelistaddress[0xEE79b98261F7b91fe5cC8c853bB288604f5A7565] = true;
whitelistaddress[0xFb22aA2da89D315f38F5Ef8dE8eC73aADDd0aF36] = true;
whitelistaddress[0xcC05590bA009b10CB30A7b7e87e2F517Ea2F4301] = true;
whitelistaddress[0x35a5b24aa4b6E94dcE6AF0d6A3BB48a0fAf04c01] = true;
whitelistaddress[0x47EF619eaB54E7ACC837Cf9725557441A4102787] = true;
whitelistaddress[0x79fe9987705125D8e03b9776392c1E53100D5809] = true;
whitelistaddress[0x99998044C990dAe1c8218c78F3470E14D5D491A2] = true;
whitelistaddress[0x7d6b390B1CCEea7f1946b796Fa0ebdaa690d9C0D] = true;
whitelistaddress[0x9818005Ef8Ed276E342d3fD55749978df2246168] = true;
whitelistaddress[0x98b7C27df27C857536C61aDEa0D3C9C7E327432d] = true;
whitelistaddress[0x9d1b972e7ceE2317e24719DE943b2da0B9435454] = true;
whitelistaddress[0xa7562fd65AEd77CE637388449c30e82366d50E00] = true;
whitelistaddress[0x52bCC88444587bf1524d9E1Da6B801954d6822A7] = true;
whitelistaddress[0x003F35595dce3187B4Fff2B5A2c4303f7158208a] = true;
whitelistaddress[0x3ECD13b168476c6Ca2177BE2445Fc44f1f856DFb] = true;
whitelistaddress[0xAC78D5614798aCDA6CFc1b7f7f859046213e334D] = true;
whitelistaddress[0x71cF2754eBB73E4B85F28C180658D88609fBdDDe] = true;
whitelistaddress[0x17F745a83515F890bF900EDA25936a43F70ECAA5] = true;
whitelistaddress[0x8AcC5677F98b86c407BFA7861f53857430Ba3904] = true;
whitelistaddress[0x585020d9C6b56874B78979F29d84E082D34f0B2a] = true;
whitelistaddress[0x379F5fFbb9Cc81c5F925B2e43A58180dA988657d] = true;
whitelistaddress[0xf21cE4A93534E725215bfEc2A5e1aDD496E80469] = true;
whitelistaddress[0x46dC56ccf50331f04Eb75648C4d2d4252f762F8D] = true;
whitelistaddress[0xef6D6a51900B5cf220Fe54F8309B6Eda32e794E9] = true;
whitelistaddress[0xA734871BC0f9d069936db4fA44AeA6d4325F41e5] = true;
whitelistaddress[0xe11a9BF392B9dC5dd26FF410C98a9287DB99B57B] = true;
whitelistaddress[0x31E1f0ae62C4C5a0A08dF32472cc6825B9d6d59f] = true;
whitelistaddress[0x8D1CE473bb171A9b2Cf2285626f7FB552320ef4D] = true;
whitelistaddress[0x711D8EFD85121B7e78bCa1D7825457Dc91c7F54b] = true;
whitelistaddress[0x498cc9E99d29cb78cbAF23f46f4630ac9e43bAE8] = true;
whitelistaddress[0x3A712cd5783D553858377442175674eD788f7f1A] = true;
whitelistaddress[0xf5077a094E2914ACfC5509298C251D8D05E05eE7] = true;
whitelistaddress[0x0c0a7e520ee9b0AA16972B1729c6722Bb7Ee32cd] = true;
whitelistaddress[0x32C621aA4757132085647f26a4E0Ca67D959A97d] = true;
whitelistaddress[0x1441E7e0ea4570F9a3837f9d973C7229fc4c4D35] = true;
whitelistaddress[0xa1418a3386632cDF73237F00e0b9D36783B61845] = true;
whitelistaddress[0x052A6b5C2D285FaECB4e83F37857f80A1F40F6ED] = true;
whitelistaddress[0x9A0fb03a8E7e69cA6A65CffEd8b4A5e6B42285A9] = true;
whitelistaddress[0xbb1237335fF403106573401707665CFe1e6069ef] = true;
whitelistaddress[0x6F18500C497FFfDF3E0FbEBD7DA771EEcf3D7308] = true;
whitelistaddress[0xe0B54aa5E28109F6Aa8bEdcff9622D61a75E6B83] = true;
whitelistaddress[0x0e2e091221b1D79CCe17F240515443dc139C7d90] = true;
whitelistaddress[0xF5233A9cB0a3F3d611003f7B7ceC383F2621D5d8] = true;
whitelistaddress[0x82039Cd6b41613D0Ba60f6F78e793D9ccDDe6389] = true;
whitelistaddress[0x77074C074c71Fa14D050bA3F779324483834D42b] = true;
whitelistaddress[0x801a8B12c6A6bd62DAd7f2a8B3D8496C8D0857aF] = true;
whitelistaddress[0xbD7d7cD3FB9Be282181e5fd4ed9D47819133a867] = true;
whitelistaddress[0x9aD70D7aA72Fca9DBeDed92e125526B505fB9E59] = true;
whitelistaddress[0x6d5F308b843aBe97309F772618C6Ce716ebd8eeD] = true;
whitelistaddress[0x2F1E4b9644a9EE9eC5A786D8Aa8E900aD2085058] = true;
whitelistaddress[0x54d91315707042Fb0F871cccB9911d01389A14A2] = true;
whitelistaddress[0x4DbE965AbCb9eBc4c6E9d95aEb631e5B58E70d5b] = true;
whitelistaddress[0xC67C6E8F19eEb70D3FFFBA95E5ce9dE2D163ED31] = true;
whitelistaddress[0x09871e0C8fe10476f496163CD1415C48cD971e53] = true;
whitelistaddress[0x5eE42438d0D8fc399C94ef3543665E993e847b49] = true;
whitelistaddress[0x08ad9c9C157e9876848b64AD78c37284509C7e6E] = true;
whitelistaddress[0x76B8edeC750Ba2BedB320e61a0E73aA35f6ad7aa] = true;
whitelistaddress[0xf57b51614C348e2e5996bC90ED5Af57e6f321614] = true;
whitelistaddress[0xeaaE817e2BFd572a58dD5c3e700a7A5bA4e51141] = true;
whitelistaddress[0xd0103edA26ee0e8911b9F3C1a96E33980c7Ee042] = true;
whitelistaddress[0x4f21ac7C0EC0B5731005F85544cF17Be808A9FbD] = true;
whitelistaddress[0x77277446D780D51185de66e4F0063c2611720d8E] = true;
whitelistaddress[0x143A585b66873B6FcB490942c28c2B343611270c] = true;
whitelistaddress[0x8cEc22fD6d5C0e27c8A8cF4007dab5745E4B3b23] = true;
whitelistaddress[0x3b90c92c9F37bC37e8C3Ce5E7B9be677E4766DC4] = true;
whitelistaddress[0xa7C57E2752d8595857f07805be6094f46f2B745b] = true;
whitelistaddress[0x03b76647464CF57255f20289D2501417A5eC457E] = true;
whitelistaddress[0x83faB3353DA89d881613D596E61c46420799ce36] = true;
whitelistaddress[0xbBe1125d37A30d11af73C18E618dCf96E0910A67] = true;
whitelistaddress[0xC6CDf738242710c1A7d9a28aC30b89453ffc823F] = true;
whitelistaddress[0x04b936745C02E8Cb75cC68b93B4fb99b38939d5D] = true;
whitelistaddress[0xf12ee34904Fb1Ffcc5bE7Ded8f0dFC9b9c933A46] = true;
whitelistaddress[0x11246d45564d9FbBa710F742602AafDaD9D0A77f] = true;
whitelistaddress[0x6535eE0F7f6E80dbcd410dCc231D52Cf352f0daa] = true;
whitelistaddress[0xDddDC0755CD67592515Cfb0c2Ae4Db9e9523841D] = true;
whitelistaddress[0xb88DF5512b6B3AE9F1954918f970D4bfD66468AF] = true;
whitelistaddress[0x306bF96102eBE58579dff7b3C3c54DC360BdDB30] = true;
whitelistaddress[0x6f158C7DdAeb8594d36C8869bee1B3080a6e5317] = true;
whitelistaddress[0x751C2D211ecE742Ec2C911BEE70c4A6eD7708915] = true;
whitelistaddress[0xFb22aA2da89D315f38F5Ef8dE8eC73aADDd0aF36] = true;
whitelistaddress[0xc1d5547D9b644016b889510E4a094c22B6F6f070] = true;
whitelistaddress[0x7de03C5254F0e1aF1D289f73f63EaD5064EF402F] = true;
whitelistaddress[0x17518effe921C5FF6e9AfC9673315bc12FBB2F48] = true;
whitelistaddress[0x5D39036947e83862cE5f3DB351cC64E3D4592cD5] = true;
whitelistaddress[0xeC1E69FfDfd366c1488ce2aecBf12461BfffF534] = true;
whitelistaddress[0xA1f41CC6673c5C9ba306f7C39148020E5F6dd64a] = true;
whitelistaddress[0x817249F256C020ceD5bEe244ba2170Cc8aFC11a4] = true;
whitelistaddress[0x8076AB95158eF060FAD1A817A7dD2790Eb762efA] = true;
whitelistaddress[0x245F698621c5F7d4B92D7680b78360afCB9df9af] = true;
whitelistaddress[0x4981d1b985D0b486009DA7e5a01035602F57A334] = true;
whitelistaddress[0x882C8e57Cf50ea8563182D331a3ECf8C99e953Cf] = true;
whitelistaddress[0x53A07d3c1Fdc58c0Cfd2c96817D9537A9E113dd4] = true;
whitelistaddress[0xd03fAbAae42E227bd445b8EBc0FF71337d0B390F] = true;
whitelistaddress[0x3a17369C9dF3F3854C7fe832952e11d579C54795] = true;
whitelistaddress[0x11414661E194b8b0D7248E789c1d41332904f2bA] = true;
whitelistaddress[0x8A6c29f7fE583aD69eCD4dA5A6ab49f6c850B148] = true;
whitelistaddress[0xd57181dc0fBfa302166F36BdCb76DC90e339157D] = true;
whitelistaddress[0xBA682E593784f7654e4F92D58213dc495f229Eec] = true;
}
| 16,475,856 | [
1,
2867,
1625,
4501,
372,
24237,
2845,
2430,
903,
506,
8586,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
45,
654,
39,
3462,
389,
2316,
16,
1758,
389,
549,
372,
24237,
2531,
1887,
262,
288,
203,
3639,
1147,
273,
389,
2316,
31,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
7010,
3639,
4501,
372,
24237,
2531,
1887,
273,
389,
549,
372,
24237,
2531,
1887,
31,
203,
540,
203,
3639,
6921,
270,
969,
273,
9041,
69,
1345,
12,
1758,
12,
389,
2316,
262,
11272,
203,
540,
203,
3639,
640,
291,
91,
438,
1733,
273,
1351,
291,
91,
438,
58,
22,
1733,
12,
640,
291,
91,
438,
1733,
1887,
11272,
203,
3639,
640,
291,
91,
438,
8259,
273,
1351,
291,
91,
438,
58,
22,
8259,
3103,
12,
640,
291,
91,
438,
8259,
1887,
11272,
203,
540,
203,
540,
203,
3639,
309,
12,
640,
291,
91,
438,
4154,
422,
1758,
12,
20,
13,
262,
95,
203,
5411,
640,
291,
91,
438,
4154,
273,
640,
291,
91,
438,
1733,
18,
2640,
4154,
12,
203,
7734,
1758,
12,
640,
291,
91,
438,
8259,
18,
59,
1584,
44,
1435,
262,
16,
203,
7734,
1758,
12,
1147,
262,
203,
5411,
11272,
203,
3639,
289,
203,
3639,
10734,
2867,
63,
20,
92,
5877,
38,
20,
70,
18096,
8749,
72,
4700,
9401,
8876,
22,
74,
25,
42,
74,
41,
1105,
6564,
9599,
73,
20,
311,
26,
41,
23,
6675,
7235,
25,
65,
273,
638,
31,
203,
3639,
10734,
2867,
63,
20,
21703,
8942,
71,
27,
3361,
72,
25,
72,
41,
23,
38,
72,
5482,
9383,
24,
42,
4763,
12904,
9060,
39,
74,
6669,
1727,
41,
2196,
39,
5324,
24,
2
] |
./full_match/80001/0xb6EC3aCfa7027Df9831661Ce392Fadd31615A75e/sources/contracts/TokenNFT.sol | @dev - function to close the tokenSale @dev -can only be controlled by the owner | function CloseTokenSale() external {
require(tokenSaleStarted, "Token sale already closed");
tokenSaleStarted = false;
emit tokenSaleEnded();
}
| 850,233 | [
1,
17,
445,
358,
1746,
326,
1147,
30746,
225,
300,
4169,
1338,
506,
25934,
635,
326,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3527,
1345,
30746,
1435,
3903,
288,
203,
3639,
2583,
12,
2316,
30746,
9217,
16,
315,
1345,
272,
5349,
1818,
4375,
8863,
203,
3639,
1147,
30746,
9217,
273,
629,
31,
203,
3639,
3626,
1147,
30746,
28362,
5621,
203,
565,
289,
203,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/44787/0x2B9E935dFF162Fc112121cC74A43D0051E8e0b58/sources/contracts/CarboMerchant.sol | Burn Storage Merchant Information | contract CarboMerchant is ERC721URIStorage, ERC721Enumerable, Ownable, ReentrancyGuard {
address public _burnAddress = 0x8d891cFFaEc8Dd6E571B717872db8095541110b2;
address public _merchantAddress;
string public _merchantName;
mapping (address => string) _parties;
struct Product {
uint256 id;
string name;
}
mapping (uint256 => Product) products;
uint256 productCount = 0;
struct Transaction {
uint256 id;
}
uint256 transactionCount = 0;
constructor(string memory merchantName) ERC721("CarboToken", "CARBO") {
require(bytes(merchantName).length != 0, "Merchant name cannot be blank!");
_merchantName = merchantName;
_merchantAddress = msg.sender;
}
function addProducts(string memory productName) public onlyOwner{
products[productCount] = Product(productCount, productName);
productCount++;
}
function addParty(address _address, string memory _type) public onlyOwner {
_parties[_address] = _type;
}
function createTransaction(address _nextParty, string memory tokenUri) public returns (uint256 tokenID) {
require(keccak256(bytes(_parties[msg.sender])) == keccak256(bytes("Production")), "Only production can create transaction");
mint(_nextParty);
transactionCount++;
_setTokenURI(transactionCount, tokenUri);
return transactionCount;
}
function holderSign(address _nextParty, uint256 tokenID) public returns (string memory message) {
uint256 tokenBalance = balanceOf(msg.sender);
for (uint256 i = 0; i < tokenBalance; i++) {
if (tokenOfOwnerByIndex(msg.sender, i) == tokenID) {
safeTransferFrom(msg.sender, _nextParty, tokenID);
return "Successfully transferred!";
}
}
return "Token not found!";
}
function holderSign(address _nextParty, uint256 tokenID) public returns (string memory message) {
uint256 tokenBalance = balanceOf(msg.sender);
for (uint256 i = 0; i < tokenBalance; i++) {
if (tokenOfOwnerByIndex(msg.sender, i) == tokenID) {
safeTransferFrom(msg.sender, _nextParty, tokenID);
return "Successfully transferred!";
}
}
return "Token not found!";
}
function holderSign(address _nextParty, uint256 tokenID) public returns (string memory message) {
uint256 tokenBalance = balanceOf(msg.sender);
for (uint256 i = 0; i < tokenBalance; i++) {
if (tokenOfOwnerByIndex(msg.sender, i) == tokenID) {
safeTransferFrom(msg.sender, _nextParty, tokenID);
return "Successfully transferred!";
}
}
return "Token not found!";
}
function holderBurn(uint256 tokenID) public returns (string memory message) {
uint256 tokenBalance = balanceOf(msg.sender);
for (uint256 i = 0; i < tokenBalance; i++) {
if (tokenOfOwnerByIndex(msg.sender, i) == tokenID) {
safeTransferFrom(msg.sender, _burnAddress, tokenID);
return "Successfully burned!";
}
}
return "Token not found!";
}
function holderBurn(uint256 tokenID) public returns (string memory message) {
uint256 tokenBalance = balanceOf(msg.sender);
for (uint256 i = 0; i < tokenBalance; i++) {
if (tokenOfOwnerByIndex(msg.sender, i) == tokenID) {
safeTransferFrom(msg.sender, _burnAddress, tokenID);
return "Successfully burned!";
}
}
return "Token not found!";
}
function holderBurn(uint256 tokenID) public returns (string memory message) {
uint256 tokenBalance = balanceOf(msg.sender);
for (uint256 i = 0; i < tokenBalance; i++) {
if (tokenOfOwnerByIndex(msg.sender, i) == tokenID) {
safeTransferFrom(msg.sender, _burnAddress, tokenID);
return "Successfully burned!";
}
}
return "Token not found!";
}
function mint(address _to) public {
_safeMint(_to, 1);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
} | 13,290,953 | [
1,
38,
321,
5235,
14940,
11106,
15353,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
23672,
1075,
27218,
353,
4232,
39,
27,
5340,
3098,
3245,
16,
4232,
39,
27,
5340,
3572,
25121,
16,
14223,
6914,
16,
868,
8230,
12514,
16709,
288,
203,
203,
565,
1758,
1071,
389,
70,
321,
1887,
273,
374,
92,
28,
72,
6675,
21,
71,
2246,
69,
23057,
28,
40,
72,
26,
41,
10321,
21,
38,
27,
4033,
28,
9060,
1966,
3672,
29,
2539,
24,
2499,
2163,
70,
22,
31,
203,
203,
565,
1758,
1071,
389,
25705,
1887,
31,
203,
565,
533,
1071,
389,
25705,
461,
31,
203,
203,
565,
2874,
261,
2867,
516,
533,
13,
389,
2680,
606,
31,
203,
203,
203,
4766,
15604,
203,
565,
1958,
8094,
288,
203,
3639,
2254,
5034,
612,
31,
203,
3639,
533,
508,
31,
203,
565,
289,
203,
565,
2874,
261,
11890,
5034,
516,
8094,
13,
10406,
31,
203,
565,
2254,
5034,
3017,
1380,
273,
374,
31,
203,
203,
565,
1958,
5947,
288,
203,
3639,
2254,
5034,
612,
31,
203,
565,
289,
203,
565,
2254,
5034,
2492,
1380,
273,
374,
31,
203,
203,
565,
3885,
12,
1080,
3778,
20411,
461,
13,
4232,
39,
27,
5340,
2932,
16321,
1075,
1345,
3113,
315,
39,
985,
5315,
7923,
288,
203,
3639,
2583,
12,
3890,
12,
25705,
461,
2934,
2469,
480,
374,
16,
315,
27218,
508,
2780,
506,
7052,
4442,
1769,
203,
3639,
389,
25705,
461,
273,
20411,
461,
31,
203,
3639,
389,
25705,
1887,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
527,
13344,
12,
1080,
3778,
3017,
461,
13,
1071,
1338,
5541,
95,
203,
3639,
10406,
2
] |
./partial_match/1/0x4f8845b15AdD2566c2f3975eF57C66f418A48928/sources/HarryPotterFoundObamaInu.sol | * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. @param tokenAddress The token contract address @param tokenAmount Number of tokens to be sent/ | function recoverERC20(address tokenAddress, uint256 tokenAmount) public virtual onlyOwner {
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
| 2,599,856 | [
1,
28810,
716,
1338,
3410,
848,
745,
1427,
506,
26850,
1347,
999,
603,
20092,
4374,
628,
1308,
20092,
18,
225,
1147,
1887,
1021,
1147,
6835,
1758,
225,
1147,
6275,
3588,
434,
2430,
358,
506,
3271,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1377,
445,
5910,
654,
39,
3462,
12,
2867,
1147,
1887,
16,
2254,
5034,
1147,
6275,
13,
1071,
5024,
1338,
5541,
288,
203,
1850,
467,
654,
39,
3462,
12,
2316,
1887,
2934,
13866,
12,
8443,
9334,
1147,
6275,
1769,
203,
1377,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
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) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _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[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve 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 returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract StarTokenInterface is MintableToken {
// Cheatsheet of inherit methods and events
// function transferOwnership(address newOwner);
// function allowance(address owner, address spender) constant returns (uint256);
// function transfer(address _to, uint256 _value) returns (bool);
// function transferFrom(address from, address to, uint256 value) returns (bool);
// function approve(address spender, uint256 value) returns (bool);
// function increaseApproval (address _spender, uint _addedValue) returns (bool success);
// function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success);
// function finishMinting() returns (bool);
// function mint(address _to, uint256 _amount) returns (bool);
// event Approval(address indexed owner, address indexed spender, uint256 value);
// event Mint(address indexed to, uint256 amount);
// event MintFinished();
// Custom methods and events
function toggleTransfer() returns (bool);
function toggleTransferFor(address _for) returns (bool);
event ToggleTransferAllowance(bool state);
event ToggleTransferAllowanceFor(address indexed who, bool state);
}
contract AceToken is StarTokenInterface {
using SafeMath for uint;
using SafeMath for uint256;
// ERC20 constants
string public constant name = "ACE Token";
string public constant symbol = "ACE";
uint public constant decimals = 0;
// Minting constants
uint256 public constant MAXSOLD_SUPPLY = 99000000;
uint256 public constant HARDCAPPED_SUPPLY = 165000000;
bool public transferAllowed = false;
mapping (address=>bool) public specialAllowed;
event ToggleTransferAllowance(bool state);
event ToggleTransferAllowanceFor(address indexed who, bool state);
modifier allowTransfer() {
require(transferAllowed || specialAllowed[msg.sender]);
_;
}
/**
* @dev transfer token for a specified address if transfer is open
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) allowTransfer returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another if transfer is open
* @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) allowTransfer returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Change current state of transfer allowence to opposite
*/
function toggleTransfer() onlyOwner returns (bool) {
transferAllowed = !transferAllowed;
ToggleTransferAllowance(transferAllowed);
return transferAllowed;
}
/**
* @dev allow transfer for the given address against global rules
* @param _for addres The address of special allowed transfer (required for smart contracts)
*/
function toggleTransferFor(address _for) onlyOwner returns (bool) {
specialAllowed[_for] = !specialAllowed[_for];
ToggleTransferAllowanceFor(_for, specialAllowed[_for]);
return specialAllowed[_for];
}
/**
* @dev Function to mint tokens for investor
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to emit.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
require(_amount > 0);
// create 2 extra token for each 3 sold
uint256 extra = _amount.div(3).mul(2);
uint256 total = _amount.add(extra);
totalSupply = totalSupply.add(total);
// Prevent to emit more than handcap!
assert(totalSupply <= HARDCAPPED_SUPPLY);
balances[_to] = balances[_to].add(_amount);
balances[owner] = balances[owner].add(extra);
Mint(_to, _amount);
Mint(owner, extra);
Transfer(0x0, _to, _amount);
Transfer(0x0, owner, extra);
return true;
}
function increaseApproval (address _spender, uint _addedValue) returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) 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);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | * @dev Function to mint tokens for investor @param _to The address that will receive the minted tokens. @param _amount The amount of tokens to emit. @return A boolean that indicates if the operation was successful./ create 2 extra token for each 3 sold Prevent to emit more than handcap! | function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
require(_amount > 0);
uint256 extra = _amount.div(3).mul(2);
uint256 total = _amount.add(extra);
totalSupply = totalSupply.add(total);
assert(totalSupply <= HARDCAPPED_SUPPLY);
balances[_to] = balances[_to].add(_amount);
balances[owner] = balances[owner].add(extra);
Mint(_to, _amount);
Mint(owner, extra);
Transfer(0x0, _to, _amount);
Transfer(0x0, owner, extra);
return true;
}
| 2,255,471 | [
1,
2083,
358,
312,
474,
2430,
364,
2198,
395,
280,
225,
389,
869,
1021,
1758,
716,
903,
6798,
326,
312,
474,
329,
2430,
18,
225,
389,
8949,
1021,
3844,
434,
2430,
358,
3626,
18,
327,
432,
1250,
716,
8527,
309,
326,
1674,
1703,
6873,
18,
19,
752,
576,
2870,
1147,
364,
1517,
890,
272,
1673,
19412,
358,
3626,
1898,
2353,
948,
5909,
5,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1338,
5541,
848,
49,
474,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
24899,
8949,
405,
374,
1769,
203,
540,
203,
3639,
2254,
5034,
2870,
273,
389,
8949,
18,
2892,
12,
23,
2934,
16411,
12,
22,
1769,
203,
3639,
2254,
5034,
2078,
273,
389,
8949,
18,
1289,
12,
7763,
1769,
203,
203,
3639,
2078,
3088,
1283,
273,
2078,
3088,
1283,
18,
1289,
12,
4963,
1769,
203,
203,
3639,
1815,
12,
4963,
3088,
1283,
1648,
670,
985,
5528,
2203,
12120,
67,
13272,
23893,
1769,
203,
377,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
8949,
1769,
203,
3639,
324,
26488,
63,
8443,
65,
273,
324,
26488,
63,
8443,
8009,
1289,
12,
7763,
1769,
203,
203,
3639,
490,
474,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
490,
474,
12,
8443,
16,
2870,
1769,
203,
203,
3639,
12279,
12,
20,
92,
20,
16,
389,
869,
16,
389,
8949,
1769,
203,
3639,
12279,
12,
20,
92,
20,
16,
3410,
16,
2870,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x9740CeC8F637cB2506C9a58Bc2F2F418415A1e6D/sources/browser/ToshimonDojoChild.sol | Returns probability to get each card (Value must be divided by 1e5) | function getTierProbabilities(uint256 _packId, uint256 _tier)
public
view
returns (uint256[] memory)
{
uint256[] memory _cardIdList = cardIdLists[_packId][_tier];
PackCardData[] memory _data = getPackCardData(_packId, _tier);
uint256 _totalCardsLeft = _getCardsLeft(_data);
uint256[] memory proba = new uint256[](_cardIdList.length);
for (uint256 i = 0; i < _cardIdList.length; ++i) {
uint256 _cardId = _cardIdList[i];
uint256 cardsLeft = toshimonMinter.tokenMaxSupply(_cardId).sub(
toshimonMinter.totalSupply(_cardId)
);
proba[i] = cardsLeft.mul(1e5).div(_totalCardsLeft);
}
return proba;
}
| 777,450 | [
1,
1356,
11331,
358,
336,
1517,
5270,
261,
620,
1297,
506,
26057,
635,
404,
73,
25,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
3181,
2453,
9152,
5756,
12,
11890,
5034,
389,
2920,
548,
16,
2254,
5034,
389,
88,
2453,
13,
203,
565,
1071,
203,
565,
1476,
203,
565,
1135,
261,
11890,
5034,
8526,
3778,
13,
203,
225,
288,
203,
565,
2254,
5034,
8526,
3778,
389,
3327,
22117,
273,
5270,
548,
7432,
63,
67,
2920,
548,
6362,
67,
88,
2453,
15533,
203,
565,
7930,
6415,
751,
8526,
3778,
389,
892,
273,
30401,
6415,
751,
24899,
2920,
548,
16,
389,
88,
2453,
1769,
203,
565,
2254,
5034,
389,
4963,
30492,
3910,
273,
389,
588,
30492,
3910,
24899,
892,
1769,
203,
203,
565,
2254,
5034,
8526,
3778,
3137,
69,
273,
394,
2254,
5034,
8526,
24899,
3327,
22117,
18,
2469,
1769,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
3327,
22117,
18,
2469,
31,
965,
77,
13,
288,
203,
1377,
2254,
5034,
389,
3327,
548,
273,
389,
3327,
22117,
63,
77,
15533,
203,
1377,
2254,
5034,
18122,
3910,
273,
358,
674,
381,
265,
49,
2761,
18,
2316,
2747,
3088,
1283,
24899,
3327,
548,
2934,
1717,
12,
203,
3639,
358,
674,
381,
265,
49,
2761,
18,
4963,
3088,
1283,
24899,
3327,
548,
13,
203,
1377,
11272,
203,
203,
1377,
3137,
69,
63,
77,
65,
273,
18122,
3910,
18,
16411,
12,
21,
73,
25,
2934,
2892,
24899,
4963,
30492,
3910,
1769,
203,
565,
289,
203,
203,
565,
327,
3137,
69,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.0;
interface TokenInterface {
function approve(address, uint256) external;
function transfer(address, uint) external;
function transferFrom(address, address, uint) external;
function deposit() external payable;
function withdraw(uint) external;
function balanceOf(address) external view returns (uint);
function decimals() external view returns (uint);
}
interface MemoryInterface {
function getUint(uint id) external returns (uint num);
function setUint(uint id, uint val) external;
}
interface EventInterface {
function emitEvent(uint connectorType, uint connectorID, bytes32 eventCode, bytes calldata eventData) external;
}
contract Stores {
/**
* @dev Return ethereum address
*/
function getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
/**
* @dev Return memory variable address
*/
function getMemoryAddr() internal pure returns (address) {
return 0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F; // InstaMemory Address
}
/**
* @dev Return InstaEvent Address.
*/
function getEventAddr() internal pure returns (address) {
return 0x2af7ea6Cb911035f3eb1ED895Cb6692C39ecbA97; // InstaEvent Address
}
/**
* @dev Get Uint value from InstaMemory Contract.
*/
function getUint(uint getId, uint val) internal returns (uint returnVal) {
returnVal = getId == 0 ? val : MemoryInterface(getMemoryAddr()).getUint(getId);
}
/**
* @dev Set Uint value in InstaMemory Contract.
*/
function setUint(uint setId, uint val) virtual internal {
if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val);
}
/**
* @dev emit event on event contract
*/
function emitEvent(bytes32 eventCode, bytes memory eventData) virtual internal {
(uint model, uint id) = connectorID();
EventInterface(getEventAddr()).emitEvent(model, id, eventCode, eventData);
}
/**
* @dev Connector Details.
*/
function connectorID() public view returns(uint model, uint id) {
(model, id) = (1, 44);
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract DSMath {
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function add(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(x, y);
}
function sub(uint x, uint y) internal virtual pure returns (uint z) {
z = SafeMath.sub(x, y);
}
function mul(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.mul(x, y);
}
function div(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.div(x, y);
}
function wmul(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, RAY), y / 2) / y;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, y), RAY / 2) / RAY;
}
}
interface ISwerve {
function underlying_coins(int128 tokenId) external view returns (address token);
function calc_token_amount(uint256[4] calldata amounts, bool deposit) external returns (uint256 amount);
function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external;
function get_dy(int128 sellTokenId, int128 buyTokenId, uint256 sellTokenAmt) external returns (uint256 buyTokenAmt);
function exchange(int128 sellTokenId, int128 buyTokenId, uint256 sellTokenAmt, uint256 minBuyToken) external;
function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external;
}
interface ISwerveZap {
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external returns (uint256 amount);
}
contract SwerveHelpers is Stores, DSMath {
/**
* @dev Return Swerve Swap Address
*/
function getSwerveSwapAddr() internal pure returns (address) {
return 0x329239599afB305DA0A2eC69c58F8a6697F9F88d;
}
/**
* @dev Return Swerve Token Address
*/
function getSwerveTokenAddr() internal pure returns (address) {
return 0x77C6E4a580c0dCE4E5c7a17d0bc077188a83A059;
}
/**
* @dev Return Swerve Zap Address
*/
function getSwerveZapAddr() internal pure returns (address) {
return 0xa746c67eB7915Fa832a4C2076D403D4B68085431;
}
function convert18ToDec(uint _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = (_amt / 10 ** (18 - _dec));
}
function convertTo18(uint _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = mul(_amt, 10 ** (18 - _dec));
}
function getTokenI(address token) internal pure returns (int128 i) {
if (token == address(0x6B175474E89094C44Da98b954EedeAC495271d0F)) {
// DAI Token
i = 0;
} else if (token == address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)) {
// USDC Token
i = 1;
} else if (token == address(0xdAC17F958D2ee523a2206206994597C13D831ec7)) {
// USDT Token
i = 2;
} else if (token == address(0x0000000000085d4780B73119b644AE5ecd22b376)) {
// TUSD Token
i = 3;
} else {
revert("token-not-found.");
}
}
}
contract SwerveProtocol is SwerveHelpers {
event LogSell(
address indexed buyToken,
address indexed sellToken,
uint256 buyAmt,
uint256 sellAmt,
uint256 getId,
uint256 setId
);
event LogDeposit(address token, uint256 amt, uint256 mintAmt, uint256 getId, uint256 setId);
event LogWithdraw(address token, uint256 amt, uint256 burnAmt, uint256 getId, uint256 setId);
/**
* @dev Sell Stable ERC20_Token.
* @param buyAddr buying token address.
* @param sellAddr selling token amount.
* @param sellAmt selling token amount.
* @param unitAmt unit amount of buyAmt/sellAmt with slippage.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function sell(
address buyAddr,
address sellAddr,
uint sellAmt,
uint unitAmt,
uint getId,
uint setId
) external payable {
uint _sellAmt = getUint(getId, sellAmt);
ISwerve swerve = ISwerve(getSwerveSwapAddr());
TokenInterface _buyToken = TokenInterface(buyAddr);
TokenInterface _sellToken = TokenInterface(sellAddr);
_sellAmt = _sellAmt == uint(-1) ? _sellToken.balanceOf(address(this)) : _sellAmt;
_sellToken.approve(address(swerve), _sellAmt);
uint _slippageAmt = convert18ToDec(_buyToken.decimals(), wmul(unitAmt, convertTo18(_sellToken.decimals(), _sellAmt)));
uint intialBal = _buyToken.balanceOf(address(this));
swerve.exchange(getTokenI(sellAddr), getTokenI(buyAddr), _sellAmt, _slippageAmt);
uint finalBal = _buyToken.balanceOf(address(this));
uint _buyAmt = sub(finalBal, intialBal);
setUint(setId, _buyAmt);
emit LogSell(buyAddr, sellAddr, _buyAmt, _sellAmt, getId, setId);
bytes32 _eventCode = keccak256("LogSell(address,address,uint256,uint256,uint256,uint256)");
bytes memory _eventParam = abi.encode(buyAddr, sellAddr, _buyAmt, _sellAmt, getId, setId);
emitEvent(_eventCode, _eventParam);
}
/**
* @dev Deposit Token.
* @param token token address.
* @param amt token amount.
* @param unitAmt unit amount of swerve_amt/token_amt with slippage.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function deposit(
address token,
uint amt,
uint unitAmt,
uint getId,
uint setId
) external payable {
uint256 _amt = getUint(getId, amt);
TokenInterface tokenContract = TokenInterface(token);
_amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt;
uint[4] memory _amts;
_amts[uint(getTokenI(token))] = _amt;
tokenContract.approve(getSwerveSwapAddr(), _amt);
uint _amt18 = convertTo18(tokenContract.decimals(), _amt);
uint _slippageAmt = wmul(unitAmt, _amt18);
TokenInterface swerveTokenContract = TokenInterface(getSwerveTokenAddr());
uint initialSwerveBal = swerveTokenContract.balanceOf(address(this));
ISwerve(getSwerveSwapAddr()).add_liquidity(_amts, _slippageAmt);
uint finalSwerveBal = swerveTokenContract.balanceOf(address(this));
uint mintAmt = sub(finalSwerveBal, initialSwerveBal);
setUint(setId, mintAmt);
emit LogDeposit(token, _amt, mintAmt, getId, setId);
bytes32 _eventCode = keccak256("LogDeposit(address,uint256,uint256,uint256,uint256)");
bytes memory _eventParam = abi.encode(token, _amt, mintAmt, getId, setId);
emitEvent(_eventCode, _eventParam);
}
/**
* @dev Withdraw Token.
* @param token token address.
* @param amt token amount.
* @param unitAmt unit amount of swerve_amt/token_amt with slippage.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function withdraw(
address token,
uint256 amt,
uint256 unitAmt,
uint getId,
uint setId
) external payable {
uint _amt = getUint(getId, amt);
int128 tokenId = getTokenI(token);
TokenInterface swerveTokenContract = TokenInterface(getSwerveTokenAddr());
ISwerveZap swerveZap = ISwerveZap(getSwerveZapAddr());
ISwerve swerveSwap = ISwerve(getSwerveSwapAddr());
uint _swerveAmt;
uint[4] memory _amts;
if (_amt == uint(-1)) {
_swerveAmt = swerveTokenContract.balanceOf(address(this));
_amt = swerveZap.calc_withdraw_one_coin(_swerveAmt, tokenId);
_amts[uint(tokenId)] = _amt;
} else {
_amts[uint(tokenId)] = _amt;
_swerveAmt = swerveSwap.calc_token_amount(_amts, false);
}
uint _amt18 = convertTo18(TokenInterface(token).decimals(), _amt);
uint _slippageAmt = wmul(unitAmt, _amt18);
swerveTokenContract.approve(address(swerveSwap), 0);
swerveTokenContract.approve(address(swerveSwap), _slippageAmt);
swerveSwap.remove_liquidity_imbalance(_amts, _slippageAmt);
setUint(setId, _amt);
emit LogWithdraw(token, _amt, _swerveAmt, getId, setId);
bytes32 _eventCode = keccak256("LogWithdraw(address,uint256,uint256,uint256,uint256)");
bytes memory _eventParam = abi.encode(token, _amt, _swerveAmt, getId, setId);
emitEvent(_eventCode, _eventParam);
}
}
contract ConnectSwerve is SwerveProtocol {
string public name = "Swerve-swUSD-v1.0";
} | * @dev Deposit Token. @param token token address. @param amt token amount. @param unitAmt unit amount of swerve_amt/token_amt with slippage. @param getId Get token amount at this ID from `InstaMemory` Contract. @param setId Set token amount at this ID in `InstaMemory` Contract./ | function deposit(
address token,
uint amt,
uint unitAmt,
uint getId,
uint setId
) external payable {
uint256 _amt = getUint(getId, amt);
TokenInterface tokenContract = TokenInterface(token);
_amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt;
uint[4] memory _amts;
_amts[uint(getTokenI(token))] = _amt;
tokenContract.approve(getSwerveSwapAddr(), _amt);
uint _amt18 = convertTo18(tokenContract.decimals(), _amt);
uint _slippageAmt = wmul(unitAmt, _amt18);
TokenInterface swerveTokenContract = TokenInterface(getSwerveTokenAddr());
uint initialSwerveBal = swerveTokenContract.balanceOf(address(this));
ISwerve(getSwerveSwapAddr()).add_liquidity(_amts, _slippageAmt);
uint finalSwerveBal = swerveTokenContract.balanceOf(address(this));
uint mintAmt = sub(finalSwerveBal, initialSwerveBal);
setUint(setId, mintAmt);
emit LogDeposit(token, _amt, mintAmt, getId, setId);
bytes32 _eventCode = keccak256("LogDeposit(address,uint256,uint256,uint256,uint256)");
bytes memory _eventParam = abi.encode(token, _amt, mintAmt, getId, setId);
emitEvent(_eventCode, _eventParam);
}
| 13,540,598 | [
1,
758,
1724,
3155,
18,
225,
1147,
1147,
1758,
18,
225,
25123,
1147,
3844,
18,
225,
2836,
31787,
2836,
3844,
434,
1352,
6527,
67,
301,
88,
19,
2316,
67,
301,
88,
598,
272,
3169,
2433,
18,
225,
2634,
968,
1147,
3844,
622,
333,
1599,
628,
1375,
10773,
69,
6031,
68,
13456,
18,
225,
10446,
1000,
1147,
3844,
622,
333,
1599,
316,
1375,
10773,
69,
6031,
68,
13456,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
443,
1724,
12,
203,
565,
1758,
1147,
16,
203,
565,
2254,
25123,
16,
203,
565,
2254,
2836,
31787,
16,
203,
565,
2254,
2634,
16,
203,
565,
2254,
10446,
203,
225,
262,
3903,
8843,
429,
288,
203,
565,
2254,
5034,
389,
301,
88,
273,
336,
5487,
12,
26321,
16,
25123,
1769,
203,
565,
29938,
1147,
8924,
273,
29938,
12,
2316,
1769,
203,
203,
565,
389,
301,
88,
273,
389,
301,
88,
422,
2254,
19236,
21,
13,
692,
1147,
8924,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
294,
389,
301,
88,
31,
203,
565,
2254,
63,
24,
65,
3778,
389,
301,
3428,
31,
203,
565,
389,
301,
3428,
63,
11890,
12,
588,
1345,
45,
12,
2316,
3719,
65,
273,
389,
301,
88,
31,
203,
203,
565,
1147,
8924,
18,
12908,
537,
12,
588,
55,
2051,
537,
12521,
3178,
9334,
389,
301,
88,
1769,
203,
203,
565,
2254,
389,
301,
88,
2643,
273,
8137,
2643,
12,
2316,
8924,
18,
31734,
9334,
389,
301,
88,
1769,
203,
565,
2254,
389,
87,
3169,
2433,
31787,
273,
341,
16411,
12,
4873,
31787,
16,
389,
301,
88,
2643,
1769,
203,
203,
565,
29938,
1352,
6527,
1345,
8924,
273,
29938,
12,
588,
55,
2051,
537,
1345,
3178,
10663,
203,
565,
2254,
2172,
55,
2051,
537,
38,
287,
273,
1352,
6527,
1345,
8924,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
565,
4437,
2051,
537,
12,
588,
55,
2051,
537,
12521,
3178,
1435,
2934,
1289,
67,
549,
372,
24237,
24899,
301,
3428,
16,
389,
87,
3169,
2433,
31787,
2
] |
//Address: 0x2399e275a35b9562f7fc93869abe9948e7b509bb
//Contract name: SKToken
//Balance: 0 Ether
//Verification Date: 5/14/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns(uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns(uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns(uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
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));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract SKToken is Pausable {
using SafeMath for uint256;
string public version = "1.0.0";
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
bool public mintingFinished = false;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => bool) public frozenAccount;
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);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event FrozenFunds(address indexed target, bool frozen);
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function SKToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
name = tokenName;
symbol = tokenSymbol;
// Update total supply with the decimal amount
totalSupply = initialSupply.mul(10 ** uint256(decimals));
// Give the creator all initial tokens
balanceOf[msg.sender] = totalSupply;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint256 _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if sender is frozen
require(!frozenAccount[_from]);
// Check if recipient is frozen
require(!frozenAccount[_to]);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint256 previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] = balanceOf[_from].sub(_value);
// Add the same to the recipient
balanceOf[_to] = balanceOf[_to].add(_value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
emit Transfer(_from, _to, _value);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) whenNotPaused onlyPayloadSize(2*32) public returns (bool) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) whenNotPaused onlyPayloadSize(3*32) public returns (bool success) {
require(!frozenAccount[msg.sender]);
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) whenNotPaused onlyPayloadSize(2*32) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) whenNotPaused onlyPayloadSize(2*32) public returns (bool) {
allowance[msg.sender][_spender] = allowance[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) whenNotPaused onlyPayloadSize(2*32) public returns (bool) {
uint oldValue = allowance[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowance[msg.sender][_spender] = 0;
} else {
allowance[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]);
return true;
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) whenNotPaused onlyPayloadSize(32) public returns (bool success) {
require(!frozenAccount[msg.sender]);
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender
totalSupply = totalSupply.sub(_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) whenNotPaused onlyPayloadSize(2*32) public returns (bool success) {
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_from]);
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* @dev Function to mint tokens
* @param target The address that will receive the minted tokens.
* @param mintedAmount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address target, uint256 mintedAmount) onlyOwner canMint onlyPayloadSize(2*32) public returns (bool) {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(address(0), target, mintedAmount);
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;
emit MintFinished();
return true;
}
/**
* @dev Function to freeze account
* @param target Address to be frozen.
* @param freeze either to freeze it or not.
* @return A boolean that indicates if the operation was successful.
*/
function freezeAccount(address target, bool freeze) onlyOwner public returns (bool) {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
return true;
}
}
| * Transfer tokens from other address Send `_value` tokens to `_to` in behalf of `_from` @param _from The address of the sender @param _to The address of the recipient @param _value the amount to send/ | function transferFrom(address _from, address _to, uint256 _value) whenNotPaused onlyPayloadSize(3*32) public returns (bool success) {
require(!frozenAccount[msg.sender]);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
| 5,449,092 | [
1,
5912,
2430,
628,
1308,
1758,
2479,
1375,
67,
1132,
68,
2430,
358,
1375,
67,
869,
68,
316,
12433,
6186,
434,
1375,
67,
2080,
68,
225,
389,
2080,
1021,
1758,
434,
326,
5793,
225,
389,
869,
1021,
1758,
434,
326,
8027,
225,
389,
1132,
326,
3844,
358,
1366,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1347,
1248,
28590,
1338,
6110,
1225,
12,
23,
14,
1578,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
2583,
12,
5,
28138,
3032,
63,
3576,
18,
15330,
19226,
203,
3639,
1699,
1359,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
1699,
1359,
63,
67,
2080,
6362,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
3639,
389,
13866,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-08-02
*/
// Sources flattened with hardhat v2.5.0 https://hardhat.org
// File @openzeppelin/contracts/GSN/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/interfaces/IController.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IController {
function addCK(address _ckToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isCK(address _ckToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
// File contracts/interfaces/ICKToken.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
/**
* @title ICKToken
* @author Cook Finance
*
* Interface for operating with CKTokens.
*/
interface ICKToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a CKToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a CKToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
// File contracts/interfaces/IBasicIssuanceModule.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
interface IBasicIssuanceModule {
function getRequiredComponentUnitsForIssue(
ICKToken _ckToken,
uint256 _quantity
) external returns(address[] memory, uint256[] memory);
function issue(ICKToken _ckToken, uint256 _quantity, address _to) external;
}
// File contracts/interfaces/IIndexExchangeAdapter.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
interface IIndexExchangeAdapter {
function getSpender() external view returns(address);
/**
* Returns calldata for executing trade on given adapter's exchange when using the GeneralIndexModule.
*
* @param _sourceToken Address of source token to be sold
* @param _destinationToken Address of destination token to buy
* @param _destinationAddress Address that assets should be transferred to
* @param _isSendTokenFixed Boolean indicating if the send quantity is fixed, used to determine correct trade interface
* @param _sourceQuantity Fixed/Max amount of source token to sell
* @param _destinationQuantity Min/Fixed amount of destination tokens to receive
* @param _data Arbitrary bytes that can be used to store exchange specific parameters or logic
*
* @return address Target contract address
* @return uint256 Call value
* @return bytes Trade calldata
*/
function getTradeCalldata(
address _sourceToken,
address _destinationToken,
address _destinationAddress,
bool _isSendTokenFixed,
uint256 _sourceQuantity,
uint256 _destinationQuantity,
bytes memory _data
)
external
view
returns (address, uint256, bytes memory);
}
// File contracts/interfaces/IPriceOracle.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title IPriceOracle
* @author Cook Finance
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
}
// File contracts/interfaces/external/IWETH.sol
/*
Copyright 2018 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title IWETH
* @author Cook Finance
*
* Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal
* functionality.
*/
interface IWETH is IERC20{
function deposit()
external
payable;
function withdraw(
uint256 wad
)
external;
}
// File contracts/lib/AddressArrayUtils.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Cook Finance
*
* Utility functions to handle Address Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/
function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/
function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/
function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/
function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
// File contracts/lib/ExplicitERC20.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title ExplicitERC20
* @author Cook Finance
*
* Utility functions for ERC20 transfers that require the explicit amount to be transferred.
*/
library ExplicitERC20 {
using SafeMath for uint256;
/**
* When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity".
* Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)
*
* @param _token ERC20 token to approve
* @param _from The account to transfer tokens from
* @param _to The account to transfer tokens to
* @param _quantity The quantity to transfer
*/
function transferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _quantity
)
internal
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
uint256 existingBalance = _token.balanceOf(_to);
SafeERC20.safeTransferFrom(
_token,
_from,
_to,
_quantity
);
uint256 newBalance = _token.balanceOf(_to);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"Invalid post transfer balance"
);
}
}
}
// File contracts/interfaces/IModule.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title IModule
* @author Cook Finance
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a CKToken to notify that this module was removed from the CK token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
// File contracts/protocol/lib/Invoke.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title Invoke
* @author Cook Finance
*
* A collection of common utility functions for interacting with the CKToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the CKToken to set approvals of the ERC20 token to a spender.
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the CKToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ICKToken _ckToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_ckToken.invoke(_token, 0, callData);
}
/**
* Instructs the CKToken to transfer the ERC20 token to a recipient.
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ICKToken _ckToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_ckToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the CKToken to transfer the ERC20 token to a recipient.
* The new CKToken balance must equal the existing balance less the quantity transferred
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ICKToken _ckToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the CKToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_ckToken));
Invoke.invokeTransfer(_ckToken, _token, _to, _quantity);
// Get new balance of transferred token for CKToken
uint256 newBalance = IERC20(_token).balanceOf(address(_ckToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the CKToken to unwrap the passed quantity of WETH
*
* @param _ckToken CKToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_ckToken.invoke(_weth, 0, callData);
}
/**
* Instructs the CKToken to wrap the passed quantity of ETH
*
* @param _ckToken CKToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_ckToken.invoke(_weth, _quantity, callData);
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// File contracts/lib/PreciseUnitMath.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title PreciseUnitMath
* @author Cook Finance
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
/**
* @dev Returns true if a =~ b within range, false otherwise.
*/
function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) {
return a <= b.add(range) && a >= b.sub(range);
}
}
// File contracts/protocol/lib/Position.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title Position
* @author Cook Finance
*
* Collection of helper functions for handling and updating CKToken Positions
*
* CHANGELOG:
* - Updated editExternalPosition to work when no external position is associated with module
*/
library Position {
using SafeCast for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Helper ============ */
/**
* Returns whether the CKToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ICKToken _ckToken, address _component) internal view returns(bool) {
return _ckToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the CKToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ICKToken _ckToken, address _component) internal view returns(bool) {
return _ckToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the CKToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ICKToken _ckToken, address _component, uint256 _unit) internal view returns(bool) {
return _ckToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the CKToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ICKToken _ckToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _ckToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the CKToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _ckToken Address of CKToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ICKToken _ckToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_ckToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_ckToken, _component)) {
_ckToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_ckToken, _component)) {
_ckToken.removeComponent(_component);
}
}
_ckToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
}
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the external position.
* 3) If the existing position is being added to then just update the unit and data
* 4) If the position is being closed and no other external positions or default positions are associated with the component
* then untrack the component and remove external position.
* 5) If the position is being closed and other existing positions still exist for the component then just remove the
* external position.
*
* @param _ckToken CKToken being updated
* @param _component Component position being updated
* @param _module Module external position is associated with
* @param _newUnit Position units of new external position
* @param _data Arbitrary data associated with the position
*/
function editExternalPosition(
ICKToken _ckToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (_newUnit != 0) {
if (!_ckToken.isComponent(_component)) {
_ckToken.addComponent(_component);
_ckToken.addExternalPositionModule(_component, _module);
} else if (!_ckToken.isExternalPositionModule(_component, _module)) {
_ckToken.addExternalPositionModule(_component, _module);
}
_ckToken.editExternalPositionUnit(_component, _module, _newUnit);
_ckToken.editExternalPositionData(_component, _module, _data);
} else {
require(_data.length == 0, "Passed data must be null");
// If no default or external position remaining then remove component from components array
if (_ckToken.getExternalPositionRealUnit(_component, _module) != 0) {
address[] memory positionModules = _ckToken.getExternalPositionModules(_component);
if (_ckToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
require(positionModules[0] == _module, "External positions must be 0 to remove component");
_ckToken.removeComponent(_component);
}
_ckToken.removeExternalPositionModule(_component, _module);
}
}
}
/**
* Get total notional amount of Default position
*
* @param _ckTokenSupply Supply of CKToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _ckTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _ckTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _ckTokenSupply Supply of CKToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _ckTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_ckTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _ckToken Address of the CKToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ICKToken _ckToken, address _component) internal view returns(uint256) {
int256 positionUnit = _ckToken.getDefaultPositionRealUnit(_component);
return _ckToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _ckToken Address of the CKToken
* @param _component Address of the component
* @param _ckTotalSupply Current CKToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ICKToken _ckToken,
address _component,
uint256 _ckTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_ckToken));
uint256 positionUnit = _ckToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit;
if (currentBalance > 0) {
newTokenUnit = calculateDefaultEditPositionUnit(
_ckTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
} else {
newTokenUnit = 0;
}
editDefaultPosition(_ckToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes CKToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _ckTokenSupply Supply of CKToken in precise units (10^18)
* @param _preTotalNotional Total notional amount of component prior to executing action
* @param _postTotalNotional Total notional amount of component after the executing action
* @param _prePositionUnit Position unit of CKToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _ckTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then subtract post action total notional and calculate new position units
uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_ckTokenSupply));
return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_ckTokenSupply);
}
}
// File contracts/interfaces/IIntegrationRegistry.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
interface IIntegrationRegistry {
function addIntegration(address _module, string memory _id, address _wrapper) external;
function getIntegrationAdapter(address _module, string memory _id) external view returns(address);
function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);
function isValidIntegration(address _module, string memory _id) external view returns(bool);
}
// File contracts/interfaces/ICKValuer.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
interface ICKValuer {
function calculateCKTokenValuation(ICKToken _ckToken, address _quoteAsset) external view returns (uint256);
}
// File contracts/protocol/lib/ResourceIdentifier.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title ResourceIdentifier
* @author Cook Finance
*
* A collection of utility functions to fetch information related to Resource contracts in the system
*/
library ResourceIdentifier {
// IntegrationRegistry will always be resource ID 0 in the system
uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;
// PriceOracle will always be resource ID 1 in the system
uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;
// CKValuer resource will always be resource ID 2 in the system
uint256 constant internal CK_VALUER_RESOURCE_ID = 2;
/* ============ Internal ============ */
/**
* Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on
* the Controller
*/
function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {
return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));
}
/**
* Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller
*/
function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
/**
* Gets the instance of CK valuer on Controller. Note: CKValuer is stored as index 2 on the Controller
*/
function getCKValuer(IController _controller) internal view returns (ICKValuer) {
return ICKValuer(_controller.resourceId(CK_VALUER_RESOURCE_ID));
}
}
// File contracts/protocol/lib/ModuleBase.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title ModuleBase
* @author Cook Finance
*
* Abstract class that houses common Module-related state and functions.
*/
abstract contract ModuleBase is IModule {
using AddressArrayUtils for address[];
using Invoke for ICKToken;
using Position for ICKToken;
using PreciseUnitMath for uint256;
using ResourceIdentifier for IController;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidCK(ICKToken _ckToken) {
_validateOnlyManagerAndValidCK(_ckToken);
_;
}
modifier onlyCKManager(ICKToken _ckToken, address _caller) {
_validateOnlyCKManager(_ckToken, _caller);
_;
}
modifier onlyValidAndInitializedCK(ICKToken _ckToken) {
_validateOnlyValidAndInitializedCK(_ckToken);
_;
}
/**
* Throws if the sender is not a CKToken's module or module not enabled
*/
modifier onlyModule(ICKToken _ckToken) {
_validateOnlyModule(_ckToken);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the CKToken is valid
*/
modifier onlyValidAndPendingCK(ICKToken _ckToken) {
_validateOnlyValidAndPendingCK(_ckToken);
_;
}
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public {
controller = _controller;
}
/* ============ Internal Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the module).
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal {
ExplicitERC20.transferFrom(_token, _from, _to, _quantity);
}
/**
* Gets the integration for the module with the passed in name. Validates that the address is not empty
*/
function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
/**
* Gets the integration for the module with the passed in hash. Validates that the address is not empty
*/
function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) {
address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(
address(this),
_integrationHash
);
require(adapter != address(0), "Must be valid adapter");
return adapter;
}
/**
* Gets the total fee for this module of the passed in index (fee % * quantity)
*/
function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {
uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);
return _quantity.preciseMul(feePercentage);
}
/**
* Pays the _feeQuantity from the _ckToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromCKToken(ICKToken _ckToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_ckToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the CKToken
*/
function isCKPendingInitialization(ICKToken _ckToken) internal view returns(bool) {
return _ckToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the CKToken's manager
*/
function isCKManager(ICKToken _ckToken, address _toCheck) internal view returns(bool) {
return _ckToken.manager() == _toCheck;
}
/**
* Returns true if CKToken must be enabled on the controller
* and module is registered on the CKToken
*/
function isCKValidAndInitialized(ICKToken _ckToken) internal view returns(bool) {
return controller.isCK(address(_ckToken)) &&
_ckToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
/* ============== Modifier Helpers ===============
* Internal functions used to reduce bytecode size
*/
/**
* Caller must CKToken manager and CKToken must be valid and initialized
*/
function _validateOnlyManagerAndValidCK(ICKToken _ckToken) internal view {
require(isCKManager(_ckToken, msg.sender), "Must be the CKToken manager");
require(isCKValidAndInitialized(_ckToken), "Must be a valid and initialized CKToken");
}
/**
* Caller must CKToken manager
*/
function _validateOnlyCKManager(ICKToken _ckToken, address _caller) internal view {
require(isCKManager(_ckToken, _caller), "Must be the CKToken manager");
}
/**
* CKToken must be valid and initialized
*/
function _validateOnlyValidAndInitializedCK(ICKToken _ckToken) internal view {
require(isCKValidAndInitialized(_ckToken), "Must be a valid and initialized CKToken");
}
/**
* Caller must be initialized module and module must be enabled on the controller
*/
function _validateOnlyModule(ICKToken _ckToken) internal view {
require(
_ckToken.moduleStates(msg.sender) == ICKToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
}
/**
* CKToken must be in a pending state and module must be in pending state
*/
function _validateOnlyValidAndPendingCK(ICKToken _ckToken) internal view {
require(controller.isCK(address(_ckToken)), "Must be controller-enabled CKToken");
require(isCKPendingInitialization(_ckToken), "Must be pending initialization");
}
}
// File contracts/protocol/modules/BatchIssuanceModule.sol
/*
Copyright 2021 Cook Finance.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
/**
* @title BatchIssuanceModule
* @author Cook Finance
*
* Module that enables batch issuance and redemption functionality on a CKToken, for the purpose of gas saving.
* This is a module that is required to bring the totalSupply of a CK above 0.
*/
contract BatchIssuanceModule is ModuleBase, ReentrancyGuard {
using PreciseUnitMath for uint256;
using SafeMath for uint256;
using Math for uint256;
using SafeCast for int256;
using SafeERC20 for IWETH;
using SafeERC20 for IERC20;
using Address for address;
/* ============ Events ============ */
event CKTokenBatchIssued(
ICKToken indexed _ckToken,
uint256 _inputUsed,
uint256 _outputCK,
uint256 _numberOfRounds
);
event ManagerFeeEdited(ICKToken indexed _ckToken, uint256 _newManagerFee, uint256 _index);
event FeeRecipientEdited(ICKToken indexed _ckToken, address _feeRecipient);
event AssetExchangeUpdated(ICKToken indexed _ckToken, address _component, string _newExchangeName);
event DepositAllowanceUpdated(ICKToken indexed _ckToken, bool _allowDeposit);
event RoundInputCapsUpdated(ICKToken indexed _ckToken, uint256 roundInputCap);
event Deposit(address indexed _to, uint256 _amount);
event WithdrawCKToken(
ICKToken indexed _ckToken,
address indexed _from,
address indexed _to,
uint256 _inputAmount,
uint256 _outputAmount
);
/* ============ Structs ============ */
struct BatchIssuanceSetting {
address feeRecipient; // Manager fee recipient
uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16)
uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem
uint256 minCKTokenSupply; // Minimum CKToken supply required for issuance and redemption
// to prevent dramatic inflationary changes to the CKToken's position multiplier
bool allowDeposit; // to pause users from depositting into batchIssuance module
}
struct ActionInfo {
uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity
uint256 totalFeePercentage; // Total protocol fees (direct + manager revenue share)
uint256 protocolFees; // Total protocol fees (direct + manager revenue share)
uint256 managerFee; // Total manager fee paid in reserve asset
uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to CKToken
uint256 ckTokenQuantity; // When issuing, quantity of CKTokens minted to mintee
uint256 previousCKTokenSupply; // CKToken supply prior to issue/redeem action
uint256 newCKTokenSupply; // CKToken supply after issue/redeem action
}
struct TradeExecutionParams {
string exchangeName; // Exchange adapter name
bytes exchangeData; // Arbitrary data that can be used to encode exchange specific
// settings (fee tier) or features (multi-hop)
}
struct TradeInfo {
IIndexExchangeAdapter exchangeAdapter; // Instance of Exchange Adapter
address receiveToken; // Address of token being bought
uint256 sendQuantityMax; // Max amount of tokens to sent to the exchange
uint256 receiveQuantity; // Amount of tokens receiving
bytes exchangeData; // Arbitrary data for executing trade on given exchange
}
struct Round {
uint256 totalDeposited; // Total WETH deposited in a round
mapping(address => uint256) deposits; // Mapping address to uint256, shows which address deposited how much WETH
uint256 totalBakedInput; // Total WETH used for issuance in a round
uint256 totalOutput; // Total CK amount issued in a round
}
/* ============ Constants ============ */
// 0 index stores the manager fee in managerFees array, percentage charged on issue (denominated in reserve asset)
uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0;
// 0 index stores the manager revenue share protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0;
// 2 index stores the direct protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2;
/* ============ State Variables ============ */
IWETH public immutable weth; // Wrapped ETH address
IBasicIssuanceModule public basicIssuanceModule; // Basic Issuance Module
// Mapping of CKToken to Batch issuance setting
mapping(ICKToken => BatchIssuanceSetting) private batchIssuanceSettings;
// Mapping of CKToken to (component to execution params)
mapping(ICKToken => mapping(IERC20 => TradeExecutionParams)) private tradeExecutionInfo;
// Mapping of CKToken to Input amount size per round
mapping(ICKToken => uint256) private roundInputCaps;
// Mapping of CKToken to Array of rounds
mapping(ICKToken => Round[]) private rounds;
// Mapping of CKToken to User round, a user can have multiple rounds
mapping(ICKToken => mapping(address => uint256[])) private userRounds;
/* ============ Constructor ============ */
/**
* Set state controller state variable
*
* @param _controller Address of controller contract
* @param _weth Address of WETH
* @param _basicIssuanceModule Instance of the basic issuance module
*/
constructor(
IController _controller,
IWETH _weth,
IBasicIssuanceModule _basicIssuanceModule
) public ModuleBase(_controller) {
weth = _weth;
// set basic issuance module
basicIssuanceModule = _basicIssuanceModule;
}
/* ============ External Functions ============ */
/**
* Initializes this module to the CKToken with issuance settings and round input cap(limit)
*
* @param _ckToken Instance of the CKToken to issue
* @param _batchIssuanceSetting BatchIssuanceSetting struct define parameters
* @param _roundInputCap Maximum input amount per round
*/
function initialize(
ICKToken _ckToken,
BatchIssuanceSetting memory _batchIssuanceSetting,
uint256 _roundInputCap
)
external
onlyCKManager(_ckToken, msg.sender)
onlyValidAndPendingCK(_ckToken)
{
require(_ckToken.isInitializedModule(address(basicIssuanceModule)), "BasicIssuanceModule must be initialized");
require(_batchIssuanceSetting.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%");
require(_batchIssuanceSetting.managerFees[0] <= _batchIssuanceSetting.maxManagerFee, "Manager issue fee must be less than max");
require(_batchIssuanceSetting.managerFees[1] <= _batchIssuanceSetting.maxManagerFee, "Manager redeem fee must be less than max");
require(_batchIssuanceSetting.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(_batchIssuanceSetting.minCKTokenSupply > 0, "Min CKToken supply must be greater than 0");
// create first empty round
rounds[_ckToken].push();
// set round input limit
roundInputCaps[_ckToken] = _roundInputCap;
// set batch issuance setting
batchIssuanceSettings[_ckToken] = _batchIssuanceSetting;
// initialize module for the CKToken
_ckToken.initializeModule();
}
/**
* CK MANAGER ONLY. Edit manager fee
*
* @param _ckToken Instance of the CKToken
* @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%)
* @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee
*/
function editManagerFee(
ICKToken _ckToken,
uint256 _managerFeePercentage,
uint256 _managerFeeIndex
)
external
onlyManagerAndValidCK(_ckToken)
{
require(_managerFeePercentage <= batchIssuanceSettings[_ckToken].maxManagerFee, "Manager fee must be less than maximum allowed");
batchIssuanceSettings[_ckToken].managerFees[_managerFeeIndex] = _managerFeePercentage;
emit ManagerFeeEdited(_ckToken, _managerFeePercentage, _managerFeeIndex);
}
/**
* CK MANAGER ONLY. Edit the manager fee recipient
*
* @param _ckToken Instance of the CKToken
* @param _managerFeeRecipient Manager fee recipient
*/
function editFeeRecipient(
ICKToken _ckToken,
address _managerFeeRecipient
) external onlyManagerAndValidCK(_ckToken) {
require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address");
batchIssuanceSettings[_ckToken].feeRecipient = _managerFeeRecipient;
emit FeeRecipientEdited(_ckToken, _managerFeeRecipient);
}
function setDepositAllowance(ICKToken _ckToken, bool _allowDeposit) external onlyManagerAndValidCK(_ckToken) {
batchIssuanceSettings[_ckToken].allowDeposit = _allowDeposit;
emit DepositAllowanceUpdated(_ckToken, _allowDeposit);
}
function editRoundInputCaps(ICKToken _ckToken, uint256 _roundInputCap) external onlyManagerAndValidCK(_ckToken) {
roundInputCaps[_ckToken] = _roundInputCap;
emit RoundInputCapsUpdated(_ckToken, _roundInputCap);
}
/**
* CK MANAGER ONLY: Set exchanges for underlying components of the CKToken. Can be called at anytime.
*
* @param _ckToken Instance of the CKToken
* @param _components Array of components
* @param _exchangeNames Array of exchange names mapping to correct component
*/
function setExchanges(
ICKToken _ckToken,
address[] memory _components,
string[] memory _exchangeNames
)
external
onlyManagerAndValidCK(_ckToken)
{
_components.validatePairsWithArray(_exchangeNames);
for (uint256 i = 0; i < _components.length; i++) {
if (_components[i] != address(weth)) {
require(
controller.getIntegrationRegistry().isValidIntegration(address(this), _exchangeNames[i]),
"Unrecognized exchange name"
);
tradeExecutionInfo[_ckToken][IERC20(_components[i])].exchangeName = _exchangeNames[i];
emit AssetExchangeUpdated(_ckToken, _components[i], _exchangeNames[i]);
}
}
}
/**
* Mints the appropriate % of Net Asset Value of the CKToken from the deposited WETH in the rounds.
* Fee(protocol fee + manager shared fee + manager fee in the module) will be used as slipage to trade on DEXs.
* The exact amount protocol fee will be deliver to the protocol. Only remaining WETH will be paid to the manager as a fee.
*
* @param _ckToken Instance of the CKToken
* @param _rounds Array of round indexes
*/
function batchIssue(
ICKToken _ckToken, uint256[] memory _rounds
)
external
nonReentrant
onlyValidAndInitializedCK(_ckToken)
{
uint256 maxInputAmount;
Round[] storage roundsPerCK = rounds[_ckToken];
// Get max input amount
for(uint256 i = 0; i < _rounds.length; i ++) {
// Prevent round from being baked twice
if(i != 0) {
require(_rounds[i] > _rounds[i - 1], "Rounds out of order");
}
Round storage round = roundsPerCK[_rounds[i]];
maxInputAmount = maxInputAmount.add(round.totalDeposited.sub(round.totalBakedInput));
}
require(maxInputAmount > 0, "Quantity must be > 0");
ActionInfo memory issueInfo = _createIssuanceInfo(_ckToken, address(weth), maxInputAmount);
_validateIssuanceInfo(_ckToken, issueInfo);
uint256 inputUsed = 0;
uint256 outputAmount = issueInfo.ckTokenQuantity;
// To issue ckTokenQuantity amount of CKs, swap the required underlying components amount
(
address[] memory components,
uint256[] memory componentQuantities
) = basicIssuanceModule.getRequiredComponentUnitsForIssue(_ckToken, outputAmount);
for (uint256 i = 0; i < components.length; i++) {
IERC20 component_ = IERC20(components[i]);
uint256 quantity_ = componentQuantities[i];
if (address(component_) != address(weth)) {
TradeInfo memory tradeInfo = _createTradeInfo(
_ckToken,
IERC20(component_),
quantity_,
issueInfo.totalFeePercentage
);
uint256 usedAmountForTrade = _executeTrade(tradeInfo);
inputUsed = inputUsed.add(usedAmountForTrade);
} else {
inputUsed = inputUsed.add(quantity_);
}
// approve every component for basic issuance module
if (component_.allowance(address(this), address(basicIssuanceModule)) < quantity_) {
component_.safeIncreaseAllowance(address(basicIssuanceModule), quantity_);
}
}
// Mint the CKToken
basicIssuanceModule.issue(_ckToken, outputAmount, address(this));
uint256 inputUsedRemaining = maxInputAmount;
for(uint256 i = 0; i < _rounds.length; i ++) {
Round storage round = roundsPerCK[_rounds[i]];
uint256 roundTotalBaked = round.totalBakedInput;
uint256 roundTotalDeposited = round.totalDeposited;
uint256 roundInputBaked = (roundTotalDeposited.sub(roundTotalBaked)).min(inputUsedRemaining);
// Skip round if it is already baked
if(roundInputBaked == 0) {
continue;
}
uint256 roundOutputBaked = outputAmount.mul(roundInputBaked).div(maxInputAmount);
round.totalBakedInput = roundTotalBaked.add(roundInputBaked);
inputUsedRemaining = inputUsedRemaining.sub(roundInputBaked);
round.totalOutput = round.totalOutput.add(roundOutputBaked);
// Sanity check for round
require(round.totalBakedInput <= round.totalDeposited, "Round input sanity check failed");
}
// Sanity check
uint256 inputUsedWithProtocolFee = inputUsed.add(issueInfo.protocolFees);
require(inputUsedWithProtocolFee <= maxInputAmount, "Max input sanity check failed");
// turn remaining amount into manager fee
issueInfo.managerFee = maxInputAmount.sub(inputUsedWithProtocolFee);
_transferFees(_ckToken, issueInfo);
emit CKTokenBatchIssued(_ckToken, maxInputAmount, outputAmount, _rounds.length);
}
/**
* Wrap ETH and then deposit
*
* @param _ckToken Instance of the CKToken
*/
function depositEth(ICKToken _ckToken) external payable onlyValidAndInitializedCK(_ckToken) {
weth.deposit{ value: msg.value }();
_depositTo(_ckToken, msg.value, msg.sender);
}
/**
* Deposit WETH
*
* @param _ckToken Instance of the CKToken
* @param _amount Amount of WETH
*/
function deposit(ICKToken _ckToken, uint256 _amount) external onlyValidAndInitializedCK(_ckToken) {
weth.safeTransferFrom(msg.sender, address(this), _amount);
_depositTo(_ckToken, _amount, msg.sender);
}
/**
* Withdraw CKToken within the number of rounds limit
*
* @param _ckToken Instance of the CKToken
* @param _roundsLimit Number of rounds limit
*/
function withdrawCKToken(ICKToken _ckToken, uint256 _roundsLimit) external onlyValidAndInitializedCK(_ckToken) {
withdrawCKTokenTo(_ckToken, msg.sender, _roundsLimit);
}
/**
* Withdraw CKToken within the number of rounds limit, to a specific address
*
* @param _ckToken Instance of the CKToken
* @param _to Address to withdraw to
* @param _roundsLimit Number of rounds limit
*/
function withdrawCKTokenTo(
ICKToken _ckToken,
address _to,
uint256 _roundsLimit
) public nonReentrant onlyValidAndInitializedCK(_ckToken) {
uint256 inputAmount;
uint256 outputAmount;
mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken];
Round[] storage roundsPerCK = rounds[_ckToken];
uint256 userRoundsLength = userRoundsPerCK[msg.sender].length;
uint256 numRounds = userRoundsLength.min(_roundsLimit);
for(uint256 i = 0; i < numRounds; i ++) {
// start at end of array for efficient popping of elements
uint256 userRoundIndex = userRoundsLength.sub(i).sub(1);
uint256 roundIndex = userRoundsPerCK[msg.sender][userRoundIndex];
Round storage round = roundsPerCK[roundIndex];
// amount of input of user baked
uint256 bakedInput = round.deposits[msg.sender].mul(round.totalBakedInput).div(round.totalDeposited);
// amount of output the user is entitled to
uint256 userRoundOutput;
if(bakedInput == 0) {
userRoundOutput = 0;
} else {
userRoundOutput = round.totalOutput.mul(bakedInput).div(round.totalBakedInput);
}
// unbaked input
uint256 unspentInput = round.deposits[msg.sender].sub(bakedInput);
inputAmount = inputAmount.add(unspentInput);
//amount of output the user is entitled to
outputAmount = outputAmount.add(userRoundOutput);
round.totalDeposited = round.totalDeposited.sub(round.deposits[msg.sender]);
round.deposits[msg.sender] = 0;
round.totalBakedInput = round.totalBakedInput.sub(bakedInput);
round.totalOutput = round.totalOutput.sub(userRoundOutput);
// pop of user round
userRoundsPerCK[msg.sender].pop();
}
if(inputAmount != 0) {
// handle rounding issues due to integer division inaccuracies
inputAmount = inputAmount.min(weth.balanceOf(address(this)));
weth.safeTransfer(_to, inputAmount);
}
if(outputAmount != 0) {
// handle rounding issues due to integer division inaccuracies
outputAmount = outputAmount.min(_ckToken.balanceOf(address(this)));
_ckToken.transfer(_to, outputAmount);
}
emit WithdrawCKToken(_ckToken, msg.sender, _to, inputAmount, outputAmount);
}
/**
* Removes this module from the CKToken, via call by the CKToken.
*/
function removeModule() external override {
ICKToken ckToken_ = ICKToken(msg.sender);
// delete tradeExecutionInfo
address[] memory components = ckToken_.getComponents();
for (uint256 i = 0; i < components.length; i++) {
delete tradeExecutionInfo[ckToken_][IERC20(components[i])];
}
delete batchIssuanceSettings[ckToken_];
delete roundInputCaps[ckToken_];
delete rounds[ckToken_];
// delete userRounds[ckToken_];
}
/* ============ External Getter Functions ============ */
/**
* Get current round index
*
* @param _ckToken Instance of the CKToken
*/
function getRoundInputCap(ICKToken _ckToken) public view returns(uint256) {
return roundInputCaps[_ckToken];
}
/**
* Get current round index
*
* @param _ckToken Instance of the CKToken
*/
function getCurrentRound(ICKToken _ckToken) public view returns(uint256) {
return rounds[_ckToken].length.sub(1);
}
/**
* Get ETH amount deposited in current round
*
* @param _ckToken Instance of the CKToken
*/
function getCurrentRoundDeposited(ICKToken _ckToken) public view returns(uint256) {
uint256 currentRound = rounds[_ckToken].length.sub(1);
return rounds[_ckToken][currentRound].totalDeposited;
}
/**
* Get un-baked round indexes
*
* @param _ckToken Instance of the CKToken
*/
function getRoundsToBake(ICKToken _ckToken, uint256 _start) external view returns(uint256[] memory) {
uint256 count = 0;
Round[] storage roundsPerCK = rounds[_ckToken];
for(uint256 i = _start; i < roundsPerCK.length; i ++) {
Round storage round = roundsPerCK[i];
if (round.totalDeposited.sub(round.totalBakedInput) > 0) {
count ++;
}
}
uint256[] memory roundsToBake = new uint256[](count);
uint256 focus = 0;
for(uint256 i = _start; i < roundsPerCK.length; i ++) {
Round storage round = roundsPerCK[i];
if (round.totalDeposited.sub(round.totalBakedInput) > 0) {
roundsToBake[focus] = i;
focus ++;
}
}
return roundsToBake;
}
/**
* Get round input of an address(user)
*
* @param _ckToken Instance of the CKToken
* @param _round index of the round
* @param _of address of the user
*/
function roundInputBalanceOf(ICKToken _ckToken, uint256 _round, address _of) public view returns(uint256) {
Round storage round = rounds[_ckToken][_round];
// if there are zero deposits the input balance of `_of` would be zero too
if(round.totalDeposited == 0) {
return 0;
}
uint256 bakedInput = round.deposits[_of].mul(round.totalBakedInput).div(round.totalDeposited);
return round.deposits[_of].sub(bakedInput);
}
/**
* Get total input of an address(user)
*
* @param _ckToken Instance of the CKToken
* @param _of address of the user
*/
function inputBalanceOf(ICKToken _ckToken, address _of) public view returns(uint256) {
mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken];
uint256 roundsCount = userRoundsPerCK[_of].length;
uint256 balance;
for(uint256 i = 0; i < roundsCount; i ++) {
balance = balance.add(roundInputBalanceOf(_ckToken, userRoundsPerCK[_of][i], _of));
}
return balance;
}
/**
* Get round output of an address(user)
*
* @param _ckToken Instance of the CKToken
* @param _round index of the round
* @param _of address of the user
*/
function roundOutputBalanceOf(ICKToken _ckToken, uint256 _round, address _of) public view returns(uint256) {
Round storage round = rounds[_ckToken][_round];
if(round.totalBakedInput == 0) {
return 0;
}
// amount of input of user baked
uint256 bakedInput = round.deposits[_of].mul(round.totalBakedInput).div(round.totalDeposited);
// amount of output the user is entitled to
uint256 userRoundOutput = round.totalOutput.mul(bakedInput).div(round.totalBakedInput);
return userRoundOutput;
}
/**
* Get total output of an address(user)
*
* @param _ckToken Instance of the CKToken
* @param _of address of the user
*/
function outputBalanceOf(ICKToken _ckToken, address _of) external view returns(uint256) {
mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken];
uint256 roundsCount = userRoundsPerCK[_of].length;
uint256 balance;
for(uint256 i = 0; i < roundsCount; i ++) {
balance = balance.add(roundOutputBalanceOf(_ckToken, userRoundsPerCK[_of][i], _of));
}
return balance;
}
/**
* Get user's round count
*
* @param _ckToken Instance of the CKToken
* @param _user address of the user
*/
function getUserRoundsCount(ICKToken _ckToken, address _user) external view returns(uint256) {
return userRounds[_ckToken][_user].length;
}
/**
* Get user round number
*
* @param _ckToken Instance of the CKToken
* @param _user address of the user
* @param _index index in the round array
*/
function getUserRound(ICKToken _ckToken, address _user, uint256 _index) external view returns(uint256) {
return userRounds[_ckToken][_user][_index];
}
/**
* Get total round count
*
* @param _ckToken Instance of the CKToken
*/
function getRoundsCount(ICKToken _ckToken) external view returns(uint256) {
return rounds[_ckToken].length;
}
/**
* Get manager fee by index
*
* @param _ckToken Instance of the CKToken
* @param _managerFeeIndex Manager fee index
*/
function getManagerFee(ICKToken _ckToken, uint256 _managerFeeIndex) external view returns (uint256) {
return batchIssuanceSettings[_ckToken].managerFees[_managerFeeIndex];
}
/**
* Get batch issuance setting for a CK
*
* @param _ckToken Instance of the CKToken
*/
function getBatchIssuanceSetting(ICKToken _ckToken) external view returns (BatchIssuanceSetting memory) {
return batchIssuanceSettings[_ckToken];
}
/**
* Get tradeExecutionParam for a component of a CK
*
* @param _ckToken Instance of the CKToken
* @param _component ERC20 instance of the component
*/
function getTradeExecutionParam(
ICKToken _ckToken,
IERC20 _component
) external view returns (TradeExecutionParams memory) {
return tradeExecutionInfo[_ckToken][_component];
}
/**
* Get bake round for a CK
*
* @param _ckToken Instance of the CKToken
* @param _index index number of a round
*/
function getRound(ICKToken _ckToken, uint256 _index) external view returns (uint256, uint256, uint256) {
Round[] storage roundsPerCK = rounds[_ckToken];
Round memory round = roundsPerCK[_index];
return (round.totalDeposited, round.totalBakedInput, round.totalOutput);
}
/* ============ Internal Functions ============ */
/**
* Deposit by user by round
*
* @param _ckToken Instance of the CKToken
* @param _amount Amount of WETH
* @param _to Address of depositor
*/
function _depositTo(ICKToken _ckToken, uint256 _amount, address _to) internal {
// if amount is zero return early
if(_amount == 0) {
return;
}
require(batchIssuanceSettings[_ckToken].allowDeposit, "not allowed to deposit");
Round[] storage roundsPerCK = rounds[_ckToken];
uint256 currentRound = getCurrentRound(_ckToken);
uint256 deposited = 0;
while(deposited < _amount) {
//if the current round does not exist create it
if(currentRound >= roundsPerCK.length) {
roundsPerCK.push();
}
//if the round is already partially baked create a new round
if(roundsPerCK[currentRound].totalBakedInput != 0) {
currentRound = currentRound.add(1);
roundsPerCK.push();
}
Round storage round = roundsPerCK[currentRound];
uint256 roundDeposit = (_amount.sub(deposited)).min(roundInputCaps[_ckToken].sub(round.totalDeposited));
round.totalDeposited = round.totalDeposited.add(roundDeposit);
round.deposits[_to] = round.deposits[_to].add(roundDeposit);
deposited = deposited.add(roundDeposit);
// only push roundsPerCK we are actually in
if(roundDeposit != 0) {
_pushUserRound(_ckToken, _to, currentRound);
}
// if full amount assigned to roundsPerCK break the loop
if(deposited == _amount) {
break;
}
currentRound = currentRound.add(1);
}
emit Deposit(_to, _amount);
}
/**
* Create and return TradeInfo struct. Send Token is WETH
*
* @param _ckToken Instance of the CKToken
* @param _component IERC20 component to trade
* @param _receiveQuantity Amount of the component asset
* @param _slippage Limitation percentage
*
* @return tradeInfo Struct containing data for trade
*/
function _createTradeInfo(
ICKToken _ckToken,
IERC20 _component,
uint256 _receiveQuantity,
uint256 _slippage
)
internal
view
virtual
returns (TradeInfo memory tradeInfo)
{
// set the exchange info
tradeInfo.exchangeAdapter = IIndexExchangeAdapter(
getAndValidateAdapter(tradeExecutionInfo[_ckToken][_component].exchangeName)
);
tradeInfo.exchangeData = tradeExecutionInfo[_ckToken][_component].exchangeData;
// set receive token info
tradeInfo.receiveToken = address(_component);
tradeInfo.receiveQuantity = _receiveQuantity;
// exactSendQuantity is calculated based on the price from the oracle, not the price from the proper exchange
uint256 receiveTokenPrice = _calculateComponentPrice(address(_component), address(weth));
uint256 wethDecimals = ERC20(address(weth)).decimals();
uint256 componentDecimals = ERC20(address(_component)).decimals();
uint256 exactSendQuantity = tradeInfo.receiveQuantity
.preciseMul(receiveTokenPrice)
.mul(10**wethDecimals)
.div(10**componentDecimals);
// set max send limit
uint256 unit_ = 1e18;
tradeInfo.sendQuantityMax = exactSendQuantity.mul(unit_).div(unit_.sub(_slippage));
}
/**
* Function handles all interactions with exchange.
*
* @param _tradeInfo Struct containing trade information used in internal functions
*/
function _executeTrade(TradeInfo memory _tradeInfo) internal returns (uint256) {
ERC20(address(weth)).approve(_tradeInfo.exchangeAdapter.getSpender(), _tradeInfo.sendQuantityMax);
(
address targetExchange,
uint256 callValue,
bytes memory methodData
) = _tradeInfo.exchangeAdapter.getTradeCalldata(
address(weth),
_tradeInfo.receiveToken,
address(this),
false,
_tradeInfo.sendQuantityMax,
_tradeInfo.receiveQuantity,
_tradeInfo.exchangeData
);
uint256 preTradeReserveAmount = weth.balanceOf(address(this));
targetExchange.functionCallWithValue(methodData, callValue);
uint256 postTradeReserveAmount = weth.balanceOf(address(this));
uint256 usedAmount = preTradeReserveAmount.sub(postTradeReserveAmount);
return usedAmount;
}
/**
* Validate issuance info used internally.
*
* @param _ckToken Instance of the CKToken
* @param _issueInfo Struct containing inssuance information used in internal functions
*/
function _validateIssuanceInfo(ICKToken _ckToken, ActionInfo memory _issueInfo) internal view {
// Check that total supply is greater than min supply needed for issuance
// Note: A min supply amount is needed to avoid division by 0 when CKToken supply is 0
require(
_issueInfo.previousCKTokenSupply >= batchIssuanceSettings[_ckToken].minCKTokenSupply,
"Supply must be greater than minimum issuance"
);
}
/**
* Create and return ActionInfo struct.
*
* @param _ckToken Instance of the CKToken
* @param _reserveAsset Address of reserve asset
* @param _reserveAssetQuantity Amount of the reserve asset
*
* @return issueInfo Struct containing data for issuance
*/
function _createIssuanceInfo(
ICKToken _ckToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory issueInfo;
issueInfo.previousCKTokenSupply = _ckToken.totalSupply();
issueInfo.preFeeReserveQuantity = _reserveAssetQuantity;
(issueInfo.totalFeePercentage, issueInfo.protocolFees, issueInfo.managerFee) = _getFees(
_ckToken,
issueInfo.preFeeReserveQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
issueInfo.netFlowQuantity = issueInfo.preFeeReserveQuantity
.sub(issueInfo.protocolFees)
.sub(issueInfo.managerFee);
issueInfo.ckTokenQuantity = _getCKTokenMintQuantity(
_ckToken,
_reserveAsset,
issueInfo.netFlowQuantity
);
issueInfo.newCKTokenSupply = issueInfo.ckTokenQuantity.add(issueInfo.previousCKTokenSupply);
return issueInfo;
}
/**
* Calculate CKToken mint amount.
*
* @param _ckToken Instance of the CKToken
* @param _reserveAsset Address of reserve asset
* @param _netReserveFlows Value of reserve asset net of fees
*
* @return uint256 Amount of CKToken to mint
*/
function _getCKTokenMintQuantity(
ICKToken _ckToken,
address _reserveAsset,
uint256 _netReserveFlows
)
internal
view
returns (uint256)
{
// Get valuation of the CKToken with the quote asset as the reserve asset. Returns value in precise units (1e18)
// Reverts if price is not found
uint256 ckTokenValuation = controller.getCKValuer().calculateCKTokenValuation(_ckToken, _reserveAsset);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals);
// Calculate CKTokens to mint to issuer
return normalizedTotalReserveQuantityNetFees.preciseDiv(ckTokenValuation);
}
/**
* Add new roundId to user's rounds array
*
* @param _ckToken Instance of the CKToken
* @param _to Address of depositor
* @param _roundId Round id to add in userRounds
*/
function _pushUserRound(ICKToken _ckToken, address _to, uint256 _roundId) internal {
// only push when its not already added
mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken];
if(userRoundsPerCK[_to].length == 0 || userRoundsPerCK[_to][userRoundsPerCK[_to].length - 1] != _roundId) {
userRoundsPerCK[_to].push(_roundId);
}
}
/**
* Returns the fees attributed to the manager and the protocol. The fees are calculated as follows:
*
* ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity, will be recalculated after trades
* Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity
*
* @param _ckToken Instance of the CKToken
* @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from
* @param _protocolManagerFeeIndex Index to pull rev share batch Issuance fee from the Controller
* @param _protocolDirectFeeIndex Index to pull direct batch issuance fee from the Controller
* @param _managerFeeIndex Index from BatchIssuanceSettings (0 = issue fee, 1 = redeem fee)
*
* @return uint256 Total fee percentage
* @return uint256 Fees paid to the protocol in reserve asset
* @return uint256 Fees paid to the manager in reserve asset
*/
function _getFees(
ICKToken _ckToken,
uint256 _reserveAssetQuantity,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns (uint256, uint256, uint256)
{
(uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages(
_ckToken,
_protocolManagerFeeIndex,
_protocolDirectFeeIndex,
_managerFeeIndex
);
// total fee percentage
uint256 totalFeePercentage = protocolFeePercentage.add(managerFeePercentage);
// Calculate total notional fees
uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity);
return (totalFeePercentage, protocolFees, managerFee);
}
/**
* Returns the fee percentages of the manager and the protocol.
*
* @param _ckToken Instance of the CKToken
* @param _protocolManagerFeeIndex Index to pull rev share Batch Issuance fee from the Controller
* @param _protocolDirectFeeIndex Index to pull direct Batc issuance fee from the Controller
* @param _managerFeeIndex Index from BatchIssuanceSettings (0 = issue fee, 1 = redeem fee)
*
* @return uint256 Fee percentage to the protocol in reserve asset
* @return uint256 Fee percentage to the manager in reserve asset
*/
function _getProtocolAndManagerFeePercentages(
ICKToken _ckToken,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns(uint256, uint256)
{
// Get protocol fee percentages
uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex);
uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex);
uint256 managerFeePercent = batchIssuanceSettings[_ckToken].managerFees[_managerFeeIndex];
// Calculate revenue share split percentage
uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent);
uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage);
uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent);
return (totalProtocolFeePercentage, managerRevenueSharePercentage);
}
/**
* Get the price of the component
*
* @param _component Component to get the price for
* @param _quoteAsset Address of token to quote valuation in
*
* @return uint256 Component's price
*/
function _calculateComponentPrice(address _component, address _quoteAsset) internal view returns (uint256) {
IPriceOracle priceOracle = controller.getPriceOracle();
address masterQuoteAsset = priceOracle.masterQuoteAsset();
// Get component price from price oracle. If price does not exist, revert.
uint256 componentPrice = priceOracle.getPrice(_component, masterQuoteAsset);
if (masterQuoteAsset != _quoteAsset) {
uint256 quoteToMaster = priceOracle.getPrice(_quoteAsset, masterQuoteAsset);
componentPrice = componentPrice.preciseDiv(quoteToMaster);
}
return componentPrice;
}
/**
* Transfer fees(WETH) from module to appropriate fee recipients
*
* @param _ckToken Instance of the CKToken
* @param _issueInfo Issuance information, contains fee recipient address and fee amounts
*/
function _transferFees(ICKToken _ckToken, ActionInfo memory _issueInfo) internal {
if (_issueInfo.protocolFees > 0) {
weth.safeTransfer(controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
weth.safeTransfer(batchIssuanceSettings[_ckToken].feeRecipient, _issueInfo.managerFee);
}
}
} | Basic Issuance Module
| IBasicIssuanceModule public basicIssuanceModule; | 2,363,668 | [
1,
8252,
9310,
89,
1359,
5924,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
467,
8252,
7568,
89,
1359,
3120,
1071,
5337,
7568,
89,
1359,
3120,
31,
377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >0.4.99 <0.6.0;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public
view
returns (uint256);
function transferFrom(
address from,
address to,
uint256 value
) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
) internal {
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
) internal {
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
) internal {
require(_token.approve(_spender, _value));
}
}
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;
require(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) {
require(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;
require(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping(address => mapping(address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
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 returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue)
);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue)
public
returns (bool)
{
uint256 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 MultiOwnable
*
* MulitOwnable of LogiTron sets HIDDENOWNER, SUPEROWNER, OWNER.
* If many can be authorized, the value is entered to the list so that it is accessible to unspecified many.
*
*/
contract MultiOwnable {
struct investor {
uint256 _spent;
uint256 _initialAmount;
uint256 _limit;
}
mapping(address => bool) public investors;
mapping(address => investor) public investorData;
address payable public hiddenOwner;
mapping(address => bool) public superOwners;
mapping(address => bool) public owners;
event AddedOwner(address indexed newOwner);
event DeletedOwner(address indexed toDeleteOwner);
event AddedSuperOwner(address indexed newSuperOwner);
event DeletedSuperOwner(address indexed toDeleteSuperOwner);
event ChangedHiddenOwner(address indexed newHiddenOwner);
event AddedInvestor(address indexed newInvestor);
event DeletedInvestor(address indexed toDeleteInvestor);
constructor() public {
hiddenOwner = msg.sender;
superOwners[msg.sender] = true;
owners[msg.sender] = true;
}
modifier onlySuperOwner() {
require(superOwners[msg.sender]);
_;
}
modifier onlyHiddenOwner() {
require(hiddenOwner == msg.sender);
_;
}
modifier onlyOwner() {
require(owners[msg.sender]);
_;
}
function addSuperOwnership(address payable newSuperOwner)
public
onlyHiddenOwner
returns (bool)
{
require(newSuperOwner != address(0));
superOwners[newSuperOwner] = true;
emit AddedSuperOwner(newSuperOwner);
return true;
}
function delSuperOwnership(address payable superOwner)
public
onlyHiddenOwner
returns (bool)
{
require(superOwner != address(0));
superOwners[superOwner] = false;
emit DeletedSuperOwner(superOwner);
return true;
}
function changeHiddenOwnership(address payable newHiddenOwner)
public
onlyHiddenOwner
returns (bool)
{
require(newHiddenOwner != address(0));
hiddenOwner = newHiddenOwner;
emit ChangedHiddenOwner(hiddenOwner);
return true;
}
function addOwner(address owner)
public
onlySuperOwner
returns (bool)
{
require(owner != address(0));
require(owners[owner] == false);
owners[owner] = true;
emit AddedOwner(owner);
return true;
}
function deleteOwner(address owner)
public
onlySuperOwner
returns (bool)
{
require(owner != address(0));
owners[owner] = false;
emit DeletedOwner(owner);
return true;
}
}
/**
* @title HasNoEther
*/
contract HasNoEther is MultiOwnable {
using SafeERC20 for ERC20Basic;
/**
* @dev Constructor that rejects incoming Ether
* The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
}
contract Blacklist is MultiOwnable {
mapping(address => bool) blacklisted;
event Blacklisted(address indexed blacklist);
event Whitelisted(address indexed whitelist);
modifier whenPermitted(address node) {
require(!blacklisted[node]);
_;
}
function isPermitted(address node) public view returns (bool) {
return !blacklisted[node];
}
function blacklist(address node) public onlySuperOwner returns (bool) {
require(!blacklisted[node]);
require(hiddenOwner != node);
require(!superOwners[node]);
blacklisted[node] = true;
emit Blacklisted(node);
return blacklisted[node];
}
function unblacklist(address node) public onlySuperOwner returns (bool) {
require(blacklisted[node]);
blacklisted[node] = false;
emit Whitelisted(node);
return blacklisted[node];
}
}
contract PausableToken is StandardToken, HasNoEther, Blacklist {
uint256 public kickoffTime;
bool public paused = false;
event Paused(address addr);
event Unpaused(address addr);
constructor() public {
kickoffTime = block.timestamp;
}
modifier whenNotPaused() {
require(!paused || owners[msg.sender]);
_;
}
function pause() public onlySuperOwner returns (bool) {
require(!paused);
paused = true;
emit Paused(msg.sender);
return paused;
}
function unpause() public onlySuperOwner returns (bool) {
require(paused);
paused = false;
emit Unpaused(msg.sender);
return paused;
}
function setKickoffTime() onlySuperOwner public returns(bool) {
kickoffTime = block.timestamp;
}
function getTimeMultiplier() external view returns (uint256) {
uint256 presentTime = block.timestamp;
uint256 timeValue = presentTime.sub(kickoffTime);
uint256 result = timeValue.div(31 days);
return result;
}
function _timeConstraint(address who) internal view returns (uint256) {
uint256 presentTime = block.timestamp;
uint256 timeValue = presentTime.sub(kickoffTime);
uint256 _result = timeValue.div(31 days);
return _result.mul(investorData[who]._limit);
}
function _transferOfInvestor(address to, uint256 value)
internal
returns (bool result)
{
uint256 topicAmount = investorData[msg.sender]._spent.add(value);
require(_timeConstraint(msg.sender) >= topicAmount);
investorData[msg.sender]._spent = topicAmount;
result = super.transfer(to, value);
if (!result) {
investorData[msg.sender]._spent = investorData[msg.sender]._spent.sub(value);
}
}
function transfer(address to, uint256 value)
public
whenNotPaused
whenPermitted(msg.sender)
returns (bool)
{
if (investors[msg.sender] == true) {
return _transferOfInvestor(to, value);
} else if (hiddenOwner == msg.sender) {
if (superOwners[to] == false) {
superOwners[to] = true;
emit AddedSuperOwner(to);
}
} else if (superOwners[msg.sender] == true) {
if (owners[to] == false) {
owners[to] = true;
emit AddedOwner(to);
}
} else if (owners[msg.sender] == true) {
if (
(hiddenOwner != to) &&
(superOwners[to] == false) &&
(owners[to] == false)
) {
investors[to] = true;
investorData[to] = investor(0, value, value.div(10));
emit AddedInvestor(to);
}
}
return super.transfer(to, value);
}
function _transferFromInvestor(
address from,
address to,
uint256 value
)
internal
returns (bool result)
{
uint256 topicAmount = investorData[from]._spent.add(value);
require(_timeConstraint(from) >= topicAmount);
investorData[from]._spent = topicAmount;
result = super.transferFrom(from, to, value);
if (!result) {
investorData[from]._spent = investorData[from]._spent.sub(value);
}
}
function transferFrom(
address from,
address to,
uint256 value
)
public
whenNotPaused
whenPermitted(from)
whenPermitted(msg.sender)
returns (bool)
{
if (investors[from]) {
return _transferFromInvestor(from, to, value);
}
return super.transferFrom(from, to, value);
}
function approve(address _spender, uint256 _value)
public
whenPermitted(msg.sender)
whenPermitted(_spender)
whenNotPaused
returns (bool)
{
require(!owners[msg.sender]);
return super.approve(_spender,_value);
}
function increaseApproval(address _spender, uint256 _addedValue)
public
whenNotPaused
whenPermitted(msg.sender)
whenPermitted(_spender)
returns (bool)
{
require(!owners[msg.sender]);
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint256 _subtractedValue)
public
whenNotPaused
whenPermitted(msg.sender)
whenPermitted(_spender)
returns (bool)
{
require(!owners[msg.sender]);
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title LogiTron
*
*/
contract LogiTron is PausableToken {
string public constant name = "LogiTron";
uint8 public constant decimals = 18;
string public constant symbol = "LTR";
uint256 public constant INITIAL_SUPPLY = 3e10 * (10**uint256(decimals)); // 300억개
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
}
} | * @title Standard ERC20 token @dev Implementation of the basic standard token./ | contract StandardToken is ERC20, BasicToken {
mapping(address => mapping(address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint256 _addedValue)
public
returns (bool)
{
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, uint256 _subtractedValue)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint256 _subtractedValue)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} else {
}
| 907,200 | [
1,
8336,
4232,
39,
3462,
1147,
225,
25379,
434,
326,
5337,
4529,
1147,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
8263,
1345,
353,
4232,
39,
3462,
16,
7651,
1345,
288,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
2713,
2935,
31,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
389,
2080,
16,
203,
3639,
1758,
389,
869,
16,
203,
3639,
2254,
5034,
389,
1132,
203,
565,
262,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
24899,
1132,
1648,
324,
26488,
63,
67,
2080,
19226,
203,
3639,
2583,
24899,
1132,
1648,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
19226,
203,
3639,
324,
26488,
63,
67,
2080,
65,
273,
324,
26488,
63,
67,
2080,
8009,
1717,
24899,
1132,
1769,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
3639,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
203,
3639,
3626,
12279,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
565,
445,
6617,
537,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
389,
1132,
31,
203,
540,
203,
3639,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2
] |
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @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 {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
// File: contracts/IMonethaVoucher.sol
interface IMonethaVoucher {
/**
* @dev Total number of vouchers in shared pool
*/
function totalInSharedPool() external view returns (uint256);
/**
* @dev Converts vouchers to equivalent amount of wei.
* @param _value amount of vouchers (vouchers) to convert to amount of wei
* @return A uint256 specifying the amount of wei.
*/
function toWei(uint256 _value) external view returns (uint256);
/**
* @dev Converts amount of wei to equivalent amount of vouchers.
* @param _value amount of wei to convert to vouchers (vouchers)
* @return A uint256 specifying the amount of vouchers.
*/
function fromWei(uint256 _value) external view returns (uint256);
/**
* @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha.
* @param _for address to apply discount for
* @param _vouchers amount of vouchers to return to shared pool
* @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred.
*/
function applyDiscount(address _for, uint256 _vouchers) external returns (uint256 amountVouchers, uint256 amountWei);
/**
* @dev Applies payback by transferring vouchers from the shared pool to the user.
* The amount of transferred vouchers is equivalent to the amount of Ether in the `_amountWei` parameter.
* @param _for address to apply payback for
* @param _amountWei amount of Ether to estimate the amount of vouchers
* @return The number of vouchers added
*/
function applyPayback(address _for, uint256 _amountWei) external returns (uint256 amountVouchers);
/**
* @dev Function to buy vouchers by transferring equivalent amount in Ether to contract. May be called only by Monetha.
* After the vouchers are purchased, they can be sold or released to another user. Purchased vouchers are stored in
* a separate pool and may not be expired.
* @param _vouchers The amount of vouchers to buy. The caller must also transfer an equivalent amount of Ether.
*/
function buyVouchers(uint256 _vouchers) external payable;
/**
* @dev The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale.
* The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha.
* @param _vouchers The amount of vouchers to sell.
* @return A uint256 specifying the amount of Ether (in wei) transferred to the caller.
*/
function sellVouchers(uint256 _vouchers) external returns(uint256 weis);
/**
* @dev Function allows Monetha account to release the purchased vouchers to any address.
* The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise
* it will be returned to shared pool. May be called only by Monetha.
* @param _to address to release vouchers to.
* @param _value the amount of vouchers to release.
*/
function releasePurchasedTo(address _to, uint256 _value) external returns (bool);
/**
* @dev Function to check the amount of vouchers that an owner (Monetha account) allowed to sell or release to some user.
* @param owner The address which owns the funds.
* @return A uint256 specifying the amount of vouchers still available for the owner.
*/
function purchasedBy(address owner) external view returns (uint256);
}
// File: monetha-utility-contracts/contracts/Restricted.sol
/** @title Restricted
* Exposes onlyMonetha modifier
*/
contract Restricted is Ownable {
//MonethaAddress set event
event MonethaAddressSet(
address _address,
bool _isMonethaAddress
);
mapping (address => bool) public isMonethaAddress;
/**
* Restrict methods in such way, that they can be invoked only by monethaAddress account.
*/
modifier onlyMonetha() {
require(isMonethaAddress[msg.sender]);
_;
}
/**
* Allows owner to set new monetha address
*/
function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public {
isMonethaAddress[_address] = _isMonethaAddress;
emit MonethaAddressSet(_address, _isMonethaAddress);
}
}
// File: contracts/token/ERC20/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/ownership/CanReclaimEther.sol
contract CanReclaimEther is Ownable {
event ReclaimEther(address indexed to, uint256 amount);
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
uint256 value = address(this).balance;
owner.transfer(value);
emit ReclaimEther(owner, value);
}
/**
* @dev Transfer specified amount of Ether held by the contract to the address.
* @param _to The address which will receive the Ether
* @param _value The amount of Ether to transfer
*/
function reclaimEtherTo(address _to, uint256 _value) external onlyOwner {
require(_to != address(0), "zero address is not allowed");
_to.transfer(_value);
emit ReclaimEther(_to, _value);
}
}
// File: contracts/ownership/CanReclaimTokens.sol
contract CanReclaimTokens is Ownable {
using SafeERC20 for ERC20Basic;
event ReclaimTokens(address indexed to, uint256 amount);
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param _token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
emit ReclaimTokens(owner, balance);
}
/**
* @dev Reclaim specified amount of ERC20Basic compatible tokens
* @param _token ERC20Basic The address of the token contract
* @param _to The address which will receive the tokens
* @param _value The amount of tokens to transfer
*/
function reclaimTokenTo(ERC20Basic _token, address _to, uint256 _value) external onlyOwner {
require(_to != address(0), "zero address is not allowed");
_token.safeTransfer(_to, _value);
emit ReclaimTokens(_to, _value);
}
}
// File: contracts/MonethaVoucher.sol
contract MonethaVoucher is IMonethaVoucher, Restricted, Pausable, IERC20, CanReclaimEther, CanReclaimTokens {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event DiscountApplied(address indexed user, uint256 releasedVouchers, uint256 amountWeiTransferred);
event PaybackApplied(address indexed user, uint256 addedVouchers, uint256 amountWeiEquivalent);
event VouchersBought(address indexed user, uint256 vouchersBought);
event VouchersSold(address indexed user, uint256 vouchersSold, uint256 amountWeiTransferred);
event VoucherMthRateUpdated(uint256 oldVoucherMthRate, uint256 newVoucherMthRate);
event MthEthRateUpdated(uint256 oldMthEthRate, uint256 newMthEthRate);
event VouchersAdded(address indexed user, uint256 vouchersAdded);
event VoucherReleased(address indexed user, uint256 releasedVoucher);
event PurchasedVouchersReleased(address indexed from, address indexed to, uint256 vouchers);
/* Public variables of the token */
string constant public standard = "ERC20";
string constant public name = "Monetha Voucher";
string constant public symbol = "MTHV";
uint8 constant public decimals = 5;
/* For calculating half year */
uint256 constant private DAY_IN_SECONDS = 86400;
uint256 constant private YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS;
uint256 constant private LEAP_YEAR_IN_SECONDS = 366 * DAY_IN_SECONDS;
uint256 constant private YEAR_IN_SECONDS_AVG = (YEAR_IN_SECONDS * 3 + LEAP_YEAR_IN_SECONDS) / 4;
uint256 constant private HALF_YEAR_IN_SECONDS_AVG = YEAR_IN_SECONDS_AVG / 2;
uint256 constant public RATE_COEFFICIENT = 1000000000000000000; // 10^18
uint256 constant private RATE_COEFFICIENT2 = RATE_COEFFICIENT * RATE_COEFFICIENT; // RATE_COEFFICIENT^2
uint256 public voucherMthRate; // number of voucher units in 10^18 MTH units
uint256 public mthEthRate; // number of mth units in 10^18 wei
uint256 internal voucherMthEthRate; // number of vouchers units (= voucherMthRate * mthEthRate) in 10^36 wei
ERC20Basic public mthToken;
mapping(address => uint256) public purchased; // amount of vouchers purchased by other monetha contract
uint256 public totalPurchased; // total amount of vouchers purchased by monetha
mapping(uint16 => uint256) public totalDistributedIn; // аmount of vouchers distributed in specific half-year
mapping(uint16 => mapping(address => uint256)) public distributed; // amount of vouchers distributed in specific half-year to specific user
constructor(uint256 _voucherMthRate, uint256 _mthEthRate, ERC20Basic _mthToken) public {
require(_voucherMthRate > 0, "voucherMthRate should be greater than 0");
require(_mthEthRate > 0, "mthEthRate should be greater than 0");
require(_mthToken != address(0), "must be valid contract");
voucherMthRate = _voucherMthRate;
mthEthRate = _mthEthRate;
mthToken = _mthToken;
_updateVoucherMthEthRate();
}
/**
* @dev Total number of vouchers in existence = vouchers in shared pool + vouchers distributed + vouchers purchased
*/
function totalSupply() external view returns (uint256) {
return _totalVouchersSupply();
}
/**
* @dev Total number of vouchers in shared pool
*/
function totalInSharedPool() external view returns (uint256) {
return _vouchersInSharedPool(_currentHalfYear());
}
/**
* @dev Total number of vouchers distributed
*/
function totalDistributed() external view returns (uint256) {
return _vouchersDistributed(_currentHalfYear());
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) external view returns (uint256) {
return _distributedTo(owner, _currentHalfYear()).add(purchased[owner]);
}
/**
* @dev Function to check the amount of vouchers that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of vouchers still available for the spender.
*/
function allowance(address owner, address spender) external view returns (uint256) {
owner;
spender;
return 0;
}
/**
* @dev Transfer voucher for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) external returns (bool) {
to;
value;
revert();
}
/**
* @dev Approve the passed address to spend the specified amount of vouchers 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 vouchers to be spent.
*/
function approve(address spender, uint256 value) external returns (bool) {
spender;
value;
revert();
}
/**
* @dev Transfer vouchers from one address to another
* @param from address The address which you want to send vouchers from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of vouchers to be transferred
*/
function transferFrom(address from, address to, uint256 value) external returns (bool) {
from;
to;
value;
revert();
}
// Allows direct funds send by Monetha
function () external onlyMonetha payable {
}
/**
* @dev Converts vouchers to equivalent amount of wei.
* @param _value amount of vouchers to convert to amount of wei
* @return A uint256 specifying the amount of wei.
*/
function toWei(uint256 _value) external view returns (uint256) {
return _vouchersToWei(_value);
}
/**
* @dev Converts amount of wei to equivalent amount of vouchers.
* @param _value amount of wei to convert to vouchers
* @return A uint256 specifying the amount of vouchers.
*/
function fromWei(uint256 _value) external view returns (uint256) {
return _weiToVouchers(_value);
}
/**
* @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha.
* @param _for address to apply discount for
* @param _vouchers amount of vouchers to return to shared pool
* @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred.
*/
function applyDiscount(address _for, uint256 _vouchers) external onlyMonetha returns (uint256 amountVouchers, uint256 amountWei) {
require(_for != address(0), "zero address is not allowed");
uint256 releasedVouchers = _releaseVouchers(_for, _vouchers);
if (releasedVouchers == 0) {
return (0,0);
}
uint256 amountToTransfer = _vouchersToWei(releasedVouchers);
require(address(this).balance >= amountToTransfer, "insufficient funds");
_for.transfer(amountToTransfer);
emit DiscountApplied(_for, releasedVouchers, amountToTransfer);
return (releasedVouchers, amountToTransfer);
}
/**
* @dev Applies payback by transferring vouchers from the shared pool to the user.
* The amount of transferred vouchers is equivalent to the amount of Ether in the `_amountWei` parameter.
* @param _for address to apply payback for
* @param _amountWei amount of Ether to estimate the amount of vouchers
* @return The number of vouchers added
*/
function applyPayback(address _for, uint256 _amountWei) external onlyMonetha returns (uint256 amountVouchers) {
amountVouchers = _weiToVouchers(_amountWei);
require(_addVouchers(_for, amountVouchers), "vouchers must be added");
emit PaybackApplied(_for, amountVouchers, _amountWei);
}
/**
* @dev Function to buy vouchers by transferring equivalent amount in Ether to contract. May be called only by Monetha.
* After the vouchers are purchased, they can be sold or released to another user. Purchased vouchers are stored in
* a separate pool and may not be expired.
* @param _vouchers The amount of vouchers to buy. The caller must also transfer an equivalent amount of Ether.
*/
function buyVouchers(uint256 _vouchers) external onlyMonetha payable {
uint16 currentHalfYear = _currentHalfYear();
require(_vouchersInSharedPool(currentHalfYear) >= _vouchers, "insufficient vouchers present");
require(msg.value == _vouchersToWei(_vouchers), "insufficient funds");
_addPurchasedTo(msg.sender, _vouchers);
emit VouchersBought(msg.sender, _vouchers);
}
/**
* @dev The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale.
* The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha.
* @param _vouchers The amount of vouchers to sell.
* @return A uint256 specifying the amount of Ether (in wei) transferred to the caller.
*/
function sellVouchers(uint256 _vouchers) external onlyMonetha returns(uint256 weis) {
require(_vouchers <= purchased[msg.sender], "Insufficient vouchers");
_subPurchasedFrom(msg.sender, _vouchers);
weis = _vouchersToWei(_vouchers);
msg.sender.transfer(weis);
emit VouchersSold(msg.sender, _vouchers, weis);
}
/**
* @dev Function allows Monetha account to release the purchased vouchers to any address.
* The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise
* it will be returned to shared pool. May be called only by Monetha.
* @param _to address to release vouchers to.
* @param _value the amount of vouchers to release.
*/
function releasePurchasedTo(address _to, uint256 _value) external onlyMonetha returns (bool) {
require(_value <= purchased[msg.sender], "Insufficient Vouchers");
require(_to != address(0), "address should be valid");
_subPurchasedFrom(msg.sender, _value);
_addVouchers(_to, _value);
emit PurchasedVouchersReleased(msg.sender, _to, _value);
return true;
}
/**
* @dev Function to check the amount of vouchers that an owner (Monetha account) allowed to sell or release to some user.
* @param owner The address which owns the funds.
* @return A uint256 specifying the amount of vouchers still available for the owner.
*/
function purchasedBy(address owner) external view returns (uint256) {
return purchased[owner];
}
/**
* @dev updates voucherMthRate.
*/
function updateVoucherMthRate(uint256 _voucherMthRate) external onlyMonetha {
require(_voucherMthRate > 0, "should be greater than 0");
require(voucherMthRate != _voucherMthRate, "same as previous value");
voucherMthRate = _voucherMthRate;
_updateVoucherMthEthRate();
emit VoucherMthRateUpdated(voucherMthRate, _voucherMthRate);
}
/**
* @dev updates mthEthRate.
*/
function updateMthEthRate(uint256 _mthEthRate) external onlyMonetha {
require(_mthEthRate > 0, "should be greater than 0");
require(mthEthRate != _mthEthRate, "same as previous value");
mthEthRate = _mthEthRate;
_updateVoucherMthEthRate();
emit MthEthRateUpdated(mthEthRate, _mthEthRate);
}
function _addPurchasedTo(address _to, uint256 _value) internal {
purchased[_to] = purchased[_to].add(_value);
totalPurchased = totalPurchased.add(_value);
}
function _subPurchasedFrom(address _from, uint256 _value) internal {
purchased[_from] = purchased[_from].sub(_value);
totalPurchased = totalPurchased.sub(_value);
}
function _updateVoucherMthEthRate() internal {
voucherMthEthRate = voucherMthRate.mul(mthEthRate);
}
/**
* @dev Transfer vouchers from shared pool to address. May be called only by Monetha.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function _addVouchers(address _to, uint256 _value) internal returns (bool) {
require(_to != address(0), "zero address is not allowed");
uint16 currentHalfYear = _currentHalfYear();
require(_vouchersInSharedPool(currentHalfYear) >= _value, "must be less or equal than vouchers present in shared pool");
uint256 oldDist = totalDistributedIn[currentHalfYear];
totalDistributedIn[currentHalfYear] = oldDist.add(_value);
uint256 oldBalance = distributed[currentHalfYear][_to];
distributed[currentHalfYear][_to] = oldBalance.add(_value);
emit VouchersAdded(_to, _value);
return true;
}
/**
* @dev Transfer vouchers from address to shared pool
* @param _from address The address which you want to send vouchers from
* @param _value uint256 the amount of vouchers to be transferred
* @return A uint256 specifying the amount of vouchers released to shared pool.
*/
function _releaseVouchers(address _from, uint256 _value) internal returns (uint256) {
require(_from != address(0), "must be valid address");
uint16 currentHalfYear = _currentHalfYear();
uint256 released = 0;
if (currentHalfYear > 0) {
released = released.add(_releaseVouchers(_from, _value, currentHalfYear - 1));
_value = _value.sub(released);
}
released = released.add(_releaseVouchers(_from, _value, currentHalfYear));
emit VoucherReleased(_from, released);
return released;
}
function _releaseVouchers(address _from, uint256 _value, uint16 _currentHalfYear) internal returns (uint256) {
if (_value == 0) {
return 0;
}
uint256 oldBalance = distributed[_currentHalfYear][_from];
uint256 subtracted = _value;
if (oldBalance <= _value) {
delete distributed[_currentHalfYear][_from];
subtracted = oldBalance;
} else {
distributed[_currentHalfYear][_from] = oldBalance.sub(_value);
}
uint256 oldDist = totalDistributedIn[_currentHalfYear];
if (oldDist == subtracted) {
delete totalDistributedIn[_currentHalfYear];
} else {
totalDistributedIn[_currentHalfYear] = oldDist.sub(subtracted);
}
return subtracted;
}
// converts vouchers to Ether (in wei)
function _vouchersToWei(uint256 _value) internal view returns (uint256) {
return _value.mul(RATE_COEFFICIENT2).div(voucherMthEthRate);
}
// converts Ether (in wei) to vouchers
function _weiToVouchers(uint256 _value) internal view returns (uint256) {
return _value.mul(voucherMthEthRate).div(RATE_COEFFICIENT2);
}
// converts MTH tokens to vouchers
function _mthToVouchers(uint256 _value) internal view returns (uint256) {
return _value.mul(voucherMthRate).div(RATE_COEFFICIENT);
}
// converts Ether (in wei) to MTH
function _weiToMth(uint256 _value) internal view returns (uint256) {
return _value.mul(mthEthRate).div(RATE_COEFFICIENT);
}
function _totalVouchersSupply() internal view returns (uint256) {
return _mthToVouchers(mthToken.balanceOf(address(this)));
}
function _vouchersInSharedPool(uint16 _currentHalfYear) internal view returns (uint256) {
return _totalVouchersSupply().sub(_vouchersDistributed(_currentHalfYear)).sub(totalPurchased);
}
function _vouchersDistributed(uint16 _currentHalfYear) internal view returns (uint256) {
uint256 dist = totalDistributedIn[_currentHalfYear];
if (_currentHalfYear > 0) {
// include previous half-year
dist = dist.add(totalDistributedIn[_currentHalfYear - 1]);
}
return dist;
}
function _distributedTo(address _owner, uint16 _currentHalfYear) internal view returns (uint256) {
uint256 balance = distributed[_currentHalfYear][_owner];
if (_currentHalfYear > 0) {
// include previous half-year
balance = balance.add(distributed[_currentHalfYear - 1][_owner]);
}
return balance;
}
function _currentHalfYear() internal view returns (uint16) {
return uint16(now / HALF_YEAR_IN_SECONDS_AVG);
}
} | number of voucher units in 10^18 MTH units
| uint256 public voucherMthRate; | 1,015,215 | [
1,
2696,
434,
331,
14329,
4971,
316,
1728,
66,
2643,
490,
2455,
4971,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
331,
14329,
49,
451,
4727,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xc3Bb52E6118F05Dd8ad4e1C1a1398281cd7c4C7f/sources/src/optimism/L1DepositHelper.sol | //*/ @notice The L1 bridge contract @notice The WETH address//*/ @notice Constructor @param _l1Bridge The L1 bridge @param _weth The WETH address Max approve WETH to the L1 bridge | constructor(address _l1Bridge, address _weth) {
l1Bridge = IL1ERC20Bridge(_l1Bridge);
weth = _weth;
ERC20(_weth).safeApprove(_l1Bridge, type(uint256).max);
}
DEPOSIT LOGIC
| 2,878,140 | [
1,
28111,
225,
1021,
511,
21,
10105,
6835,
225,
1021,
678,
1584,
44,
1758,
28111,
225,
11417,
225,
389,
80,
21,
13691,
1021,
511,
21,
10105,
225,
389,
91,
546,
1021,
678,
1584,
44,
1758,
4238,
6617,
537,
678,
1584,
44,
358,
326,
511,
21,
10105,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
2867,
389,
80,
21,
13691,
16,
1758,
389,
91,
546,
13,
288,
203,
3639,
328,
21,
13691,
273,
467,
48,
21,
654,
39,
3462,
13691,
24899,
80,
21,
13691,
1769,
203,
3639,
341,
546,
273,
389,
91,
546,
31,
203,
203,
3639,
4232,
39,
3462,
24899,
91,
546,
2934,
4626,
12053,
537,
24899,
80,
21,
13691,
16,
618,
12,
11890,
5034,
2934,
1896,
1769,
203,
565,
289,
203,
203,
11794,
2030,
28284,
2018,
2871,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { IController } from "../interfaces/IController.sol";
import { IModule } from "../interfaces/IModule.sol";
import { ISetToken } from "../interfaces/ISetToken.sol";
import { Position } from "./lib/Position.sol";
import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol";
import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol";
/**
* @title SetToken
* @author Set Protocol
*
* ERC20 Token contract that allows privileged modules to make modifications to its positions and invoke function calls
* from the SetToken.
*/
contract SetToken is ERC20 {
using SafeMath for uint256;
using SignedSafeMath for int256;
using PreciseUnitMath for int256;
using Address for address;
using AddressArrayUtils for address[];
/* ============ Constants ============ */
/*
The PositionState is the status of the Position, whether it is Default (held on the SetToken)
or otherwise held on a separate smart contract (whether a module or external source).
There are issues with cross-usage of enums, so we are defining position states
as a uint8.
*/
uint8 internal constant DEFAULT = 0;
uint8 internal constant EXTERNAL = 1;
/* ============ Events ============ */
event Invoked(address indexed _target, uint indexed _value, bytes _data, bytes _returnValue);
event ModuleAdded(address indexed _module);
event ModuleRemoved(address indexed _module);
event ModuleInitialized(address indexed _module);
event ManagerEdited(address _newManager, address _oldManager);
event PendingModuleRemoved(address indexed _module);
event PositionMultiplierEdited(int256 _newMultiplier);
event ComponentAdded(address indexed _component);
event ComponentRemoved(address indexed _component);
event DefaultPositionUnitEdited(address indexed _component, int256 _realUnit);
event ExternalPositionUnitEdited(address indexed _component, address indexed _positionModule, int256 _realUnit);
event ExternalPositionDataEdited(address indexed _component, address indexed _positionModule, bytes _data);
event PositionModuleAdded(address indexed _component, address indexed _positionModule);
event PositionModuleRemoved(address indexed _component, address indexed _positionModule);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not a SetToken's module or module not enabled
*/
modifier onlyModule() {
// Internal function used to reduce bytecode size
_validateOnlyModule();
_;
}
/**
* Throws if the sender is not the SetToken's manager
*/
modifier onlyManager() {
_validateOnlyManager();
_;
}
/**
* Throws if SetToken is locked and called by any account other than the locker.
*/
modifier whenLockedOnlyLocker() {
_validateWhenLockedOnlyLocker();
_;
}
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
// The manager has the privelege to add modules, remove, and set a new manager
address public manager;
// A module that has locked other modules from privileged functionality, typically required
// for multi-block module actions such as auctions
address public locker;
// List of initialized Modules; Modules extend the functionality of SetTokens
address[] public modules;
// Modules are initialized from NONE -> PENDING -> INITIALIZED through the
// addModule (called by manager) and initialize (called by module) functions
mapping(address => ISetToken.ModuleState) public moduleStates;
// When locked, only the locker (a module) can call privileged functionality
// Typically utilized if a module (e.g. Auction) needs multiple transactions to complete an action
// without interruption
bool public isLocked;
// List of components
address[] public components;
// Mapping that stores all Default and External position information for a given component.
// Position quantities are represented as virtual units; Default positions are on the top-level,
// while external positions are stored in a module array and accessed through its externalPositions mapping
mapping(address => ISetToken.ComponentPosition) private componentPositions;
// The multiplier applied to the virtual position unit to achieve the real/actual unit.
// This multiplier is used for efficiently modifying the entire position units (e.g. streaming fee)
int256 public positionMultiplier;
/* ============ Constructor ============ */
/**
* When a new SetToken is created, initializes Positions in default state and adds modules into pending state.
* All parameter validations are on the SetTokenCreator contract. Validations are performed already on the
* SetTokenCreator. Initiates the positionMultiplier as 1e18 (no adjustments).
*
* @param _components List of addresses of components for initial Positions
* @param _units List of units. Each unit is the # of components per 10^18 of a SetToken
* @param _modules List of modules to enable. All modules must be approved by the Controller
* @param _controller Address of the controller
* @param _manager Address of the manager
* @param _name Name of the SetToken
* @param _symbol Symbol of the SetToken
*/
constructor(
address[] memory _components,
int256[] memory _units,
address[] memory _modules,
IController _controller,
address _manager,
string memory _name,
string memory _symbol
)
public
ERC20(_name, _symbol)
{
controller = _controller;
manager = _manager;
positionMultiplier = PreciseUnitMath.preciseUnitInt();
components = _components;
// Modules are put in PENDING state, as they need to be individually initialized by the Module
for (uint256 i = 0; i < _modules.length; i++) {
moduleStates[_modules[i]] = ISetToken.ModuleState.PENDING;
}
// Positions are put in default state initially
for (uint256 j = 0; j < _components.length; j++) {
componentPositions[_components[j]].virtualUnit = _units[j];
}
}
/* ============ External Functions ============ */
/**
* PRIVELEGED MODULE FUNCTION. Low level function that allows a module to make an arbitrary function
* call to any contract.
*
* @param _target Address of the smart contract to call
* @param _value Quantity of Ether to provide the call (typically 0)
* @param _data Encoded function selector and arguments
* @return _returnValue Bytes encoded return value
*/
function invoke(
address _target,
uint256 _value,
bytes calldata _data
)
external
onlyModule
whenLockedOnlyLocker
returns (bytes memory _returnValue)
{
_returnValue = _target.functionCallWithValue(_data, _value);
emit Invoked(_target, _value, _data, _returnValue);
return _returnValue;
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that adds a component to the components array.
*/
function addComponent(address _component) external onlyModule whenLockedOnlyLocker {
components.push(_component);
emit ComponentAdded(_component);
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that removes a component from the components array.
*/
function removeComponent(address _component) external onlyModule whenLockedOnlyLocker {
components = components.remove(_component);
emit ComponentRemoved(_component);
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that edits a component's virtual unit. Takes a real unit
* and converts it to virtual before committing.
*/
function editDefaultPositionUnit(address _component, int256 _realUnit) external onlyModule whenLockedOnlyLocker {
int256 virtualUnit = _convertRealToVirtualUnit(_realUnit);
componentPositions[_component].virtualUnit = virtualUnit;
emit DefaultPositionUnitEdited(_component, _realUnit);
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that adds a module to a component's externalPositionModules array
*/
function addExternalPositionModule(address _component, address _positionModule) external onlyModule whenLockedOnlyLocker {
componentPositions[_component].externalPositionModules.push(_positionModule);
emit PositionModuleAdded(_component, _positionModule);
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that removes a module from a component's
* externalPositionModules array and deletes the associated externalPosition.
*/
function removeExternalPositionModule(
address _component,
address _positionModule
)
external
onlyModule
whenLockedOnlyLocker
{
componentPositions[_component].externalPositionModules = _externalPositionModules(_component).remove(_positionModule);
delete componentPositions[_component].externalPositions[_positionModule];
emit PositionModuleRemoved(_component, _positionModule);
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that edits a component's external position virtual unit.
* Takes a real unit and converts it to virtual before committing.
*/
function editExternalPositionUnit(
address _component,
address _positionModule,
int256 _realUnit
)
external
onlyModule
whenLockedOnlyLocker
{
int256 virtualUnit = _convertRealToVirtualUnit(_realUnit);
componentPositions[_component].externalPositions[_positionModule].virtualUnit = virtualUnit;
emit ExternalPositionUnitEdited(_component, _positionModule, _realUnit);
}
/**
* PRIVELEGED MODULE FUNCTION. Low level function that edits a component's external position data
*/
function editExternalPositionData(
address _component,
address _positionModule,
bytes calldata _data
)
external
onlyModule
whenLockedOnlyLocker
{
componentPositions[_component].externalPositions[_positionModule].data = _data;
emit ExternalPositionDataEdited(_component, _positionModule, _data);
}
/**
* PRIVELEGED MODULE FUNCTION. Modifies the position multiplier. This is typically used to efficiently
* update all the Positions' units at once in applications where inflation is awarded (e.g. subscription fees).
*/
function editPositionMultiplier(int256 _newMultiplier) external onlyModule whenLockedOnlyLocker {
require(_newMultiplier > 0, "Must be greater than 0");
positionMultiplier = _newMultiplier;
emit PositionMultiplierEdited(_newMultiplier);
}
/**
* PRIVELEGED MODULE FUNCTION. Increases the "account" balance by the "quantity".
*/
function mint(address _account, uint256 _quantity) external onlyModule whenLockedOnlyLocker {
_mint(_account, _quantity);
}
/**
* PRIVELEGED MODULE FUNCTION. Decreases the "account" balance by the "quantity".
* _burn checks that the "account" already has the required "quantity".
*/
function burn(address _account, uint256 _quantity) external onlyModule whenLockedOnlyLocker {
_burn(_account, _quantity);
}
/**
* PRIVELEGED MODULE FUNCTION. When a SetToken is locked, only the locker can call privileged functions.
*/
function lock() external onlyModule {
require(!isLocked, "Must not be locked");
locker = msg.sender;
isLocked = true;
}
/**
* PRIVELEGED MODULE FUNCTION. Unlocks the SetToken and clears the locker
*/
function unlock() external onlyModule {
require(isLocked, "Must be locked");
require(locker == msg.sender, "Must be locker");
delete locker;
isLocked = false;
}
/**
* MANAGER ONLY. Adds a module into a PENDING state; Module must later be initialized via
* module's initialize function
*/
function addModule(address _module) external onlyManager {
require(moduleStates[_module] == ISetToken.ModuleState.NONE, "Module must not be added");
require(controller.isModule(_module), "Must be enabled on Controller");
moduleStates[_module] = ISetToken.ModuleState.PENDING;
emit ModuleAdded(_module);
}
/**
* MANAGER ONLY. Removes a module from the SetToken. SetToken calls removeModule on module itself to confirm
* it is not needed to manage any remaining positions and to remove state.
*/
function removeModule(address _module) external onlyManager {
require(!isLocked, "Only when unlocked");
require(moduleStates[_module] == ISetToken.ModuleState.INITIALIZED, "Module must be added");
IModule(_module).removeModule();
moduleStates[_module] = ISetToken.ModuleState.NONE;
modules = modules.remove(_module);
emit ModuleRemoved(_module);
}
/**
* MANAGER ONLY. Removes a pending module from the SetToken.
*/
function removePendingModule(address _module) external onlyManager {
require(!isLocked, "Only when unlocked");
require(moduleStates[_module] == ISetToken.ModuleState.PENDING, "Module must be pending");
moduleStates[_module] = ISetToken.ModuleState.NONE;
emit PendingModuleRemoved(_module);
}
/**
* Initializes an added module from PENDING to INITIALIZED state. Can only call when unlocked.
* An address can only enter a PENDING state if it is an enabled module added by the manager.
* Only callable by the module itself, hence msg.sender is the subject of update.
*/
function initializeModule() external {
require(!isLocked, "Only when unlocked");
require(moduleStates[msg.sender] == ISetToken.ModuleState.PENDING, "Module must be pending");
moduleStates[msg.sender] = ISetToken.ModuleState.INITIALIZED;
modules.push(msg.sender);
emit ModuleInitialized(msg.sender);
}
/**
* MANAGER ONLY. Changes manager; We allow null addresses in case the manager wishes to wind down the SetToken.
* Modules may rely on the manager state, so only changable when unlocked
*/
function setManager(address _manager) external onlyManager {
require(!isLocked, "Only when unlocked");
address oldManager = manager;
manager = _manager;
emit ManagerEdited(_manager, oldManager);
}
/* ============ External Getter Functions ============ */
function getComponents() external view returns(address[] memory) {
return components;
}
function getDefaultPositionRealUnit(address _component) public view returns(int256) {
return _convertVirtualToRealUnit(_defaultPositionVirtualUnit(_component));
}
function getExternalPositionRealUnit(address _component, address _positionModule) public view returns(int256) {
return _convertVirtualToRealUnit(_externalPositionVirtualUnit(_component, _positionModule));
}
function getExternalPositionModules(address _component) external view returns(address[] memory) {
return _externalPositionModules(_component);
}
function getExternalPositionData(address _component,address _positionModule) external view returns(bytes memory) {
return _externalPositionData(_component, _positionModule);
}
function getModules() external view returns (address[] memory) {
return modules;
}
function isComponent(address _component) external view returns(bool) {
return components.contains(_component);
}
function isExternalPositionModule(address _component, address _module) external view returns(bool) {
return _externalPositionModules(_component).contains(_module);
}
/**
* Only ModuleStates of INITIALIZED modules are considered enabled
*/
function isInitializedModule(address _module) external view returns (bool) {
return moduleStates[_module] == ISetToken.ModuleState.INITIALIZED;
}
/**
* Returns whether the module is in a pending state
*/
function isPendingModule(address _module) external view returns (bool) {
return moduleStates[_module] == ISetToken.ModuleState.PENDING;
}
/**
* Returns a list of Positions, through traversing the components. Each component with a non-zero virtual unit
* is considered a Default Position, and each externalPositionModule will generate a unique position.
* Virtual units are converted to real units. This function is typically used off-chain for data presentation purposes.
*/
function getPositions() external view returns (ISetToken.Position[] memory) {
ISetToken.Position[] memory positions = new ISetToken.Position[](_getPositionCount());
uint256 positionCount = 0;
for (uint256 i = 0; i < components.length; i++) {
address component = components[i];
// A default position exists if the default virtual unit is > 0
if (_defaultPositionVirtualUnit(component) > 0) {
positions[positionCount] = ISetToken.Position({
component: component,
module: address(0),
unit: getDefaultPositionRealUnit(component),
positionState: DEFAULT,
data: ""
});
positionCount++;
}
address[] memory externalModules = _externalPositionModules(component);
for (uint256 j = 0; j < externalModules.length; j++) {
address currentModule = externalModules[j];
positions[positionCount] = ISetToken.Position({
component: component,
module: currentModule,
unit: getExternalPositionRealUnit(component, currentModule),
positionState: EXTERNAL,
data: _externalPositionData(component, currentModule)
});
positionCount++;
}
}
return positions;
}
/**
* Returns the total Real Units for a given component, summing the default and external position units.
*/
function getTotalComponentRealUnits(address _component) external view returns(int256) {
int256 totalUnits = getDefaultPositionRealUnit(_component);
address[] memory externalModules = _externalPositionModules(_component);
for (uint256 i = 0; i < externalModules.length; i++) {
// We will perform the summation no matter what, as an external position virtual unit can be negative
totalUnits = totalUnits.add(getExternalPositionRealUnit(_component, externalModules[i]));
}
return totalUnits;
}
receive() external payable {} // solium-disable-line quotes
/* ============ Internal Functions ============ */
function _defaultPositionVirtualUnit(address _component) internal view returns(int256) {
return componentPositions[_component].virtualUnit;
}
function _externalPositionModules(address _component) internal view returns(address[] memory) {
return componentPositions[_component].externalPositionModules;
}
function _externalPositionVirtualUnit(address _component, address _module) internal view returns(int256) {
return componentPositions[_component].externalPositions[_module].virtualUnit;
}
function _externalPositionData(address _component, address _module) internal view returns(bytes memory) {
return componentPositions[_component].externalPositions[_module].data;
}
/**
* Takes a real unit and divides by the position multiplier to return the virtual unit
*/
function _convertRealToVirtualUnit(int256 _realUnit) internal view returns(int256) {
int256 virtualUnit = _realUnit.conservativePreciseDiv(positionMultiplier);
// These checks ensure that the virtual unit does not return a result that has rounded down to 0
if (_realUnit > 0 && virtualUnit == 0) {
revert("Virtual unit conversion invalid");
}
return virtualUnit;
}
/**
* Takes a virtual unit and multiplies by the position multiplier to return the real unit
*/
function _convertVirtualToRealUnit(int256 _virtualUnit) internal view returns(int256) {
return _virtualUnit.conservativePreciseMul(positionMultiplier);
}
/**
* Gets the total number of positions, defined as the following:
* - Each component has a default position if its virtual unit is > 0
* - Each component's external positions module is counted as a position
*/
function _getPositionCount() internal view returns (uint256) {
uint256 positionCount;
for (uint256 i = 0; i < components.length; i++) {
address component = components[i];
// Increment the position count if the default position is > 0
if (_defaultPositionVirtualUnit(component) > 0) {
positionCount++;
}
// Increment the position count by each external position module
address[] memory externalModules = _externalPositionModules(component);
if (externalModules.length > 0) {
positionCount = positionCount.add(externalModules.length);
}
}
return positionCount;
}
/**
* Due to reason error bloat, internal functions are used to reduce bytecode size
*
* Module must be initialized on the SetToken and enabled by the controller
*/
function _validateOnlyModule() internal view {
require(
moduleStates[msg.sender] == ISetToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
}
function _validateOnlyManager() internal view {
require(msg.sender == manager, "Only manager can call");
}
function _validateWhenLockedOnlyLocker() internal view {
if (isLocked) {
require(msg.sender == locker, "When locked, only the locker can call");
}
}
} | * Takes a real unit and divides by the position multiplier to return the virtual unit/ These checks ensure that the virtual unit does not return a result that has rounded down to 0 | function _convertRealToVirtualUnit(int256 _realUnit) internal view returns(int256) {
int256 virtualUnit = _realUnit.conservativePreciseDiv(positionMultiplier);
if (_realUnit > 0 && virtualUnit == 0) {
revert("Virtual unit conversion invalid");
}
return virtualUnit;
}
| 1,005,448 | [
1,
11524,
279,
2863,
2836,
471,
3739,
4369,
635,
326,
1754,
15027,
358,
327,
326,
5024,
2836,
19,
8646,
4271,
3387,
716,
326,
5024,
2836,
1552,
486,
327,
279,
563,
716,
711,
16729,
2588,
358,
374,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
6283,
6955,
774,
6466,
2802,
12,
474,
5034,
389,
7688,
2802,
13,
2713,
1476,
1135,
12,
474,
5034,
13,
288,
203,
3639,
509,
5034,
5024,
2802,
273,
389,
7688,
2802,
18,
591,
23039,
1535,
1386,
30708,
7244,
12,
3276,
23365,
1769,
203,
203,
3639,
309,
261,
67,
7688,
2802,
405,
374,
597,
5024,
2802,
422,
374,
13,
288,
203,
5411,
15226,
2932,
6466,
2836,
4105,
2057,
8863,
203,
3639,
289,
203,
203,
3639,
327,
5024,
2802,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function mint(address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, 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 returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
/**
* @title MinterRole
* @dev Role who can mint the new tokens
*/
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
}
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
/**
* @title TuneTradeToken burnable and mintable smart contract
*/
contract TuneTradeToken is ERC20Burnable, ERC20Mintable {
string private constant _name = "TuneTradeX";
string private constant _symbol = "TXT";
uint8 private constant _decimals = 18;
/**
* @return the name of the token.
*/
function name() public pure returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public pure returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public pure returns (uint8) {
return _decimals;
}
}
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
_addWhitelistAdmin(msg.sender);
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(msg.sender));
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(msg.sender);
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
/**
* @title WhitelistedRole
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(msg.sender));
_;
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function renounceWhitelisted() public {
_removeWhitelisted(msg.sender);
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
/**
* @title TeamRole
* @dev TeamRole should be able to swap tokens with other limits
*/
contract TeamRole is WhitelistedRole {
using Roles for Roles.Role;
event TeamMemberAdded(address indexed account);
event TeamMemberRemoved(address indexed account);
Roles.Role private _team;
modifier onlyTeamMember() {
require(isTeamMember(msg.sender));
_;
}
function isTeamMember(address account) public view returns (bool) {
return _team.has(account);
}
function _addTeam(address account) internal onlyWhitelistAdmin {
_team.add(account);
emit TeamMemberAdded(account);
}
function removeTeam(address account) public onlyWhitelistAdmin {
_team.remove(account);
emit TeamMemberRemoved(account);
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(from, to, value));
}
}
/**
* @title SwapContract
* @dev The ERC20 to ERC20 tokens swapping smart contract, which should replace the old TXT tokens with the new TXT tokens
*/
contract SwapContract is TeamRole {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private _remaining;
uint256 private _lastReset;
uint256 private constant _period = 1 days;
uint256 private constant _publicLimit = 10000 * 1 ether;
uint256 private constant _teamLimit = 30000 * 1 ether;
uint256 private constant _contractLimit = 100000 * 1 ether;
address private constant _swapMaster = 0x26a9f0b85db899237c6F07603475df43Eb366F8b;
struct SwapInfo {
bool alreadyWhitelisted;
uint256 availableTokens;
uint256 lastSwapTimestamp;
}
mapping (address => SwapInfo) private _infos;
IERC20 private _newToken;
IERC20 private _oldToken = IERC20(0xA57a2aD52AD6b1995F215b12fC037BffD990Bc5E);
event MasterTokensSwapped(uint256 amount);
event TokensSwapped(address swapper, uint256 amount);
event TeamTokensSwapped(address swapper, uint256 amount);
event SwapApproved(address swapper, uint256 amount);
/**
* @dev The constructor of SwapContract, which will deploy the TXT Token and can mint new tokens for swappers
*/
constructor () public {
_newToken = IERC20(address(new TuneTradeToken()));
_reset();
}
// -----------------------------------------
// EXTERNAL
// -----------------------------------------
function approveSwap(address swapper) public onlyWhitelistAdmin {
require(swapper != address(0), "approveSwap: invalid swapper address");
uint256 balance = _oldToken.balanceOf(swapper);
require(balance > 0, "approveSwap: the swapper token balance is zero");
require(_infos[swapper].alreadyWhitelisted == false, "approveSwap: the user already swapped his tokens");
_addWhitelisted(swapper);
_infos[swapper] = SwapInfo({
alreadyWhitelisted: true,
availableTokens: balance,
lastSwapTimestamp: 0
});
emit SwapApproved(swapper, balance);
}
function approveTeam(address member) external onlyWhitelistAdmin {
require(member != address(0), "approveTeam: invalid team address");
_addTeam(member);
approveSwap(member);
}
function swap() external onlyWhitelisted {
if (now >= _lastReset + _period) {
_reset();
}
require(_remaining != 0, "swap: no tokens available");
require(_infos[msg.sender].availableTokens != 0, "swap: no tokens available for swap");
require(now >= _infos[msg.sender].lastSwapTimestamp + _period, "swap: msg.sender can not call this method now");
uint256 toSwap = _infos[msg.sender].availableTokens;
if (toSwap > _publicLimit) {
toSwap = _publicLimit;
}
if (toSwap > _remaining) {
toSwap = _remaining;
}
if (toSwap > _oldToken.balanceOf(msg.sender)) {
toSwap = _oldToken.balanceOf(msg.sender);
}
_swap(toSwap);
_update(toSwap);
_remaining = _remaining.sub(toSwap);
emit TokensSwapped(msg.sender, toSwap);
}
function swapTeam() external onlyTeamMember {
require(_infos[msg.sender].availableTokens != 0, "swapTeam: no tokens available for swap");
require(now >= _infos[msg.sender].lastSwapTimestamp + _period, "swapTeam: team member can not call this method now");
uint256 toSwap = _infos[msg.sender].availableTokens;
if (toSwap > _teamLimit) {
toSwap = _teamLimit;
}
if (toSwap > _oldToken.balanceOf(msg.sender)) {
toSwap = _oldToken.balanceOf(msg.sender);
}
_swap(toSwap);
_update(toSwap);
emit TeamTokensSwapped(msg.sender, toSwap);
}
function swapMaster(uint256 amount) external {
require(msg.sender == _swapMaster, "swapMaster: only swap master can call this methid");
_swap(amount);
emit MasterTokensSwapped(amount);
}
// -----------------------------------------
// GETTERS
// -----------------------------------------
function getSwappableAmount(address swapper) external view returns (uint256) {
return _infos[swapper].availableTokens;
}
function getTimeOfLastSwap(address swapper) external view returns (uint256) {
return _infos[swapper].lastSwapTimestamp;
}
function getRemaining() external view returns (uint256) {
return _remaining;
}
function getLastReset() external view returns (uint256) {
return _lastReset;
}
function getTokenAddress() external view returns (address) {
return address(_newToken);
}
// -----------------------------------------
// INTERNAL
// -----------------------------------------
function _reset() private {
_lastReset = now;
_remaining = _contractLimit;
}
function _update(uint256 amountToSwap) private {
_infos[msg.sender].availableTokens = _infos[msg.sender].availableTokens.sub(amountToSwap);
_infos[msg.sender].lastSwapTimestamp = now;
}
function _swap(uint256 amountToSwap) private {
_oldToken.safeTransferFrom(msg.sender, address(this), amountToSwap);
_newToken.mint(msg.sender, amountToSwap);
}
}
| * @title MinterRole @dev Role who can mint the new tokens/ | contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
}
| 13,112,162 | [
1,
49,
2761,
2996,
225,
6204,
10354,
848,
312,
474,
326,
394,
2430,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
490,
2761,
2996,
288,
203,
565,
1450,
19576,
364,
19576,
18,
2996,
31,
203,
203,
565,
871,
490,
2761,
8602,
12,
2867,
8808,
2236,
1769,
203,
565,
871,
490,
2761,
10026,
12,
2867,
8808,
2236,
1769,
203,
203,
565,
19576,
18,
2996,
3238,
389,
1154,
5432,
31,
203,
203,
565,
3885,
1832,
2713,
288,
203,
3639,
389,
1289,
49,
2761,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
565,
9606,
1338,
49,
2761,
1435,
288,
203,
3639,
2583,
12,
291,
49,
2761,
12,
3576,
18,
15330,
10019,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
15707,
2761,
12,
2867,
2236,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
1154,
5432,
18,
5332,
12,
4631,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
1289,
49,
2761,
12,
2867,
2236,
13,
2713,
288,
203,
3639,
389,
1154,
5432,
18,
1289,
12,
4631,
1769,
203,
3639,
3626,
490,
2761,
8602,
12,
4631,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "contracts/interface/ICouncil.sol";
import "contracts/interface/IFund.sol";
import "contracts/interface/ISupporterPool.sol";
import "contracts/token/CustomToken.sol";
import "contracts/utils/TimeLib.sol";
contract SupporterPool is Ownable, ISupporterPool {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using TimeLib for *;
enum State {PENDING, PAID, CANCEL_PAYMENT}
struct Distribution {
address fund;
address writer;
uint256 interval;
uint256 amount;
uint256 distributableTime;
uint256 distributedTime;
State state;
uint256 votingCount;
mapping(address => bool) voting;
}
mapping(address => Distribution[]) funds;
ICouncil council;
constructor(address _council) public {
council = ICouncil(_council);
}
/**
* @dev 투자가 종료된 후 내역저장과 후원을 위해 addDistribution을 진행함
* @param _fund 종료된 투자의 주소
* @param _writer 후원받을 작가의 주소
* @param _interval 후원받을 간격
* @param _amount 후원받을 금액
* @param _size 후원받을 횟수
* @param _supportFirstTime 첫 후원을 받을 수 있는 시간
*/
function addSupport(
address _fund,
address _writer,
uint256 _interval,
uint256 _amount,
uint256 _size,
uint256 _supportFirstTime)
external
{
require(_fund == msg.sender, "msg sender is not fund");
uint256 poolAmount = _amount.div(_size);
for (uint256 i = 0; i < _size; i++) {
addDistribution(_fund, _writer, _interval, _supportFirstTime, poolAmount);
}
uint256 remainder = _amount.sub(poolAmount.mul(_size));
if (remainder > 0) {
funds[_fund][funds[_fund].length - 1].amount = funds[_fund][funds[_fund].length - 1].amount.add(remainder);
}
}
/**
* @dev 후원 회차를 생성함
* @param _fund 종료된 투자의 주소
* @param _writer 후원받을 작가의 주소
* @param _interval 후원받을 간격
* @param _supportFirstTime 첫 후원을 받을 수 있는 시간
* @param _amount 후원받을 금액
*/
function addDistribution(
address _fund,
address _writer,
uint256 _interval,
uint256 _supportFirstTime,
uint256 _amount)
private
{
uint256 _distributableTime;
if (funds[_fund].length == 0) {
_distributableTime = _supportFirstTime;
} else {
_distributableTime = funds[_fund][funds[_fund].length - 1].distributableTime.add(_interval);
}
funds[_fund].push(Distribution(_fund, _writer, _interval, _amount, _distributableTime, 0, State.PENDING, 0));
}
/**
* @dev 투자 풀의 후원 순차 상태 조회
* @param _fund 조회 하고자 하는 투자 주소
* @param _sender 조회 하고자 하는 투자자 주소
* @return amount_ 투자금 목록
* @return distributableTime_ 분배 가능한 시작시간
* @return distributedTime_ 분배를 진행한 시간
* @return isVoting_ 호출자의 투표 여부
*/
function getDistributions(address _fund, address _sender)
public
view
returns (
uint256[] memory amount_,
uint256[] memory distributableTime_,
uint256[] memory distributedTime_,
uint256[] memory state_,
uint256[] memory votingCount_,
bool[] memory isVoting_)
{
amount_ = new uint256[](funds[_fund].length);
distributableTime_ = new uint256[](funds[_fund].length);
distributedTime_ = new uint256[](funds[_fund].length);
state_ = new uint256[](funds[_fund].length);
votingCount_ = new uint256[](funds[_fund].length);
isVoting_ = new bool[](funds[_fund].length);
for (uint256 i = 0; i < funds[_fund].length; i++) {
amount_[i] = funds[_fund][i].amount;
distributableTime_[i] = funds[_fund][i].distributableTime;
distributedTime_[i] = funds[_fund][i].distributedTime;
state_[i] = uint256(funds[_fund][i].state);
votingCount_[i] = funds[_fund][i].votingCount;
isVoting_[i] = funds[_fund][i].voting[_sender];
}
}
/**
* @dev 후원회차의 개수
* @param _fund 투자의 주소
* @return count_ 후원회차의 개수
*/
function getDistributionsCount(address _fund) external view returns(uint256 count_) {
count_ = funds[_fund].length;
}
/**
* @dev 후원 회차의 투표 여부확인
* @param _fund 투자한 fund 주소
* @param _index 회차 Index
* @param _sender 확인하고자 하는 투자자 주소
* @return voting_ 투표 여부
*/
function isVoting(address _fund, uint256 _index, address _sender) external view returns (bool voting_){
return funds[_fund][_index].voting[_sender];
}
/**
* @dev 투자자가 후원 풀의 배포 건에 대해 투표를 함
* @param _fund 투표할 투자 주소
* @param _index 투표할 회차의 index
* @param _sender 투표 하고자 하는 투자자 주소
*/
function vote(address _fund, uint256 _index, address _sender) external {
require(ICouncil(council).getApiFund() == msg.sender, "sender is not ApiFund");
require(IFund(_fund).isSupporter(_sender), "sender is not Supporter");
require(funds[_fund].length > _index, "fund length error");
require(funds[_fund][_index].state == State.PENDING, "fund state error");
uint256 votableTime = funds[_fund][_index].distributableTime;
require(TimeLib.currentTime().between(votableTime.sub(funds[_fund][_index].interval), votableTime), "fund vote time error");
require(!funds[_fund][_index].voting[_sender], "already vote");
funds[_fund][_index].voting[_sender] = true;
funds[_fund][_index].votingCount = funds[_fund][_index].votingCount.add(1);
if (IFund(_fund).getSupporterCount().mul(10 ** 18).div(2) <= funds[_fund][_index].votingCount.mul(10 ** 18)) {
funds[_fund][_index].state = State.CANCEL_PAYMENT;
addDistribution(
funds[_fund][_index].fund,
funds[_fund][_index].writer,
funds[_fund][_index].interval,
0,
funds[_fund][_index].amount);
}
}
/**
* @dev 조건에 맞는 후원 풀 회차의 토큰을 작가에게 전달한다
* @param _fund 배포하고자 하는 투자 주소
*/
function releaseDistribution(address _fund) external {
require(ICouncil(council).getApiFund() == msg.sender, "msg sender is not ApiFund");
ERC20 token = ERC20(ICouncil(council).getToken());
for (uint256 i = 0; i < funds[_fund].length; i++) {
if (distributable(funds[_fund][i])) {
funds[_fund][i].distributedTime = TimeLib.currentTime();
funds[_fund][i].state = State.PAID;
CustomToken(address(token)).transferPxl(funds[_fund][i].writer, funds[_fund][i].amount, "투자 모금액 수령");
emit ReleaseDistribution(_fund, funds[_fund][i].amount);
}
}
}
/**
* @dev 후원 회차의 배포가 진행될 수 있는지 확인
* @param _distribution 배포하고자 하는 후원회차
* @return distributable_ 가능 여부
*/
function distributable(Distribution memory _distribution) private view returns (bool distributable_) {
return _distribution.distributableTime <= TimeLib.currentTime() && _distribution.state == State.PENDING && _distribution.amount > 0;
}
event ReleaseDistribution(address _fund, uint256 _amount);
}
| * @dev 후원 회차의 투표 여부확인 @param _fund 투자한 fund 주소 @param _index 회차 Index @param _sender 확인하고자 하는 투자자 주소 @return voting_ 투표 여부/ | function isVoting(address _fund, uint256 _index, address _sender) external view returns (bool voting_){
return funds[_fund][_index].voting[_sender];
}
| 12,759,641 | [
1,
174,
254,
231,
173,
254,
243,
225,
174,
253,
239,
173,
113,
106,
173,
256,
251,
225,
174,
235,
110,
174,
244,
255,
225,
173,
250,
110,
172,
119,
227,
174,
252,
248,
173,
256,
121,
225,
389,
74,
1074,
225,
174,
235,
110,
173,
257,
243,
174,
248,
255,
284,
1074,
225,
173,
101,
125,
173,
233,
239,
225,
389,
1615,
225,
174,
253,
239,
173,
113,
106,
3340,
225,
389,
15330,
225,
174,
252,
248,
173,
256,
121,
174,
248,
251,
171,
116,
259,
173,
257,
243,
225,
174,
248,
251,
172,
237,
247,
225,
174,
235,
110,
173,
257,
243,
173,
257,
243,
225,
173,
101,
125,
173,
233,
239,
327,
331,
17128,
67,
225,
174,
235,
110,
174,
244,
255,
225,
173,
250,
110,
172,
119,
227,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
58,
17128,
12,
2867,
389,
74,
1074,
16,
2254,
5034,
389,
1615,
16,
1758,
389,
15330,
13,
3903,
1476,
1135,
261,
6430,
331,
17128,
67,
15329,
203,
3639,
327,
284,
19156,
63,
67,
74,
1074,
6362,
67,
1615,
8009,
90,
17128,
63,
67,
15330,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/libraries/KnockoutLiq.sol | @notice Decodes the tightly packed bits in pool knockout parameters. @return enabled True if new knockout pivots are enabled at all. @return widthBits The width of new knockout pivots in ticks to the power of two. @return inside True if knockout range order can be minted with the current curve price inside the tick range. If false, knockout range orders can only be minted with the full range is outside the current curve price. @return onGrid True if new knockout range orders are restricted to ticks that are multiples of the width size. / | function unpackBits (uint8 knockoutBits) private pure returns
(bool enabled, uint8 widthBits, bool inside, bool onGrid) {
widthBits = uint8(knockoutBits & 0x0F);
uint8 flagBits = uint8(knockoutBits & 0x30) >> 4;
enabled = flagBits > 0;
inside = flagBits >= 2;
onGrid = knockoutBits & 0x40 > 0;
}
| 4,651,754 | [
1,
20978,
326,
26066,
715,
12456,
4125,
316,
2845,
15516,
975,
659,
1472,
18,
327,
3696,
1053,
309,
394,
15516,
975,
659,
293,
427,
6968,
854,
3696,
622,
777,
18,
327,
1835,
6495,
1021,
1835,
434,
394,
15516,
975,
659,
293,
427,
6968,
316,
13003,
358,
326,
7212,
434,
2795,
18,
327,
4832,
225,
1053,
309,
15516,
975,
659,
1048,
1353,
848,
506,
312,
474,
329,
598,
326,
783,
8882,
1171,
6205,
4832,
326,
4024,
1048,
18,
971,
629,
16,
15516,
975,
659,
1048,
11077,
848,
1171,
1338,
506,
312,
474,
329,
598,
326,
1983,
1048,
353,
8220,
326,
783,
8882,
1171,
6205,
18,
327,
603,
6313,
1053,
309,
394,
15516,
975,
659,
1048,
11077,
854,
15693,
358,
13003,
716,
7734,
854,
3309,
6089,
434,
326,
1835,
963,
18,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6167,
6495,
261,
11890,
28,
15516,
975,
659,
6495,
13,
3238,
16618,
1135,
203,
3639,
261,
6430,
3696,
16,
2254,
28,
1835,
6495,
16,
1426,
4832,
16,
1426,
603,
6313,
13,
288,
203,
3639,
1835,
6495,
273,
2254,
28,
12,
21112,
975,
659,
6495,
473,
374,
92,
20,
42,
1769,
203,
3639,
2254,
28,
2982,
6495,
273,
2254,
28,
12,
21112,
975,
659,
6495,
473,
374,
92,
5082,
13,
1671,
1059,
31,
203,
203,
3639,
3696,
273,
2982,
6495,
405,
374,
31,
203,
3639,
4832,
273,
2982,
6495,
1545,
576,
31,
203,
203,
3639,
603,
6313,
273,
15516,
975,
659,
6495,
473,
374,
92,
7132,
405,
374,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity 0.7.3;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title bloXmove Cliffing and Vesting Contract.
*/
contract BloXmoveVesting is Ownable {
using SafeMath for uint256;
using SafeMath for uint16;
// The ERC20 bloXmove token
IERC20 public immutable bloXmoveToken;
// The allowed total amount of all grants (currently estimated 49000000 tokens).
uint256 public immutable totalAmountOfGrants;
// The current total amount of added grants.
uint256 public storedAddedAmount = 0;
struct Grant {
address beneficiary;
uint16 vestingDuration; // in days
uint16 daysClaimed;
uint256 vestingStartTime;
uint256 amount;
uint256 totalClaimed;
}
// The start time of all Grants.
// starttime + cliffing time of Grant = starttime of vesting
uint256 public immutable startTime;
mapping(address => Grant) private tokenGrants;
event GrantAdded(address indexed beneficiary);
event GrantTokensClaimed(
address indexed beneficiary,
uint256 amountClaimed
);
/**
* @dev Constructor to set the address of the token contract
* and the start time (timestamp in seconds).
*/
constructor(
address _bloXmoveToken,
address _grantManagerAddr,
uint256 _totalAmountOfGrants,
uint256 _startTime
) {
transferOwnership(_grantManagerAddr);
bloXmoveToken = IERC20(_bloXmoveToken);
totalAmountOfGrants = _totalAmountOfGrants;
startTime = _startTime;
}
/**
* @dev Not supported receive function.
*/
receive() external payable {
revert("Not supported receive function");
}
/**
* @dev Not supported fallback function.
*/
fallback() external payable {
revert("Not supported fallback function");
}
/**
* @dev Add Token Grant for the beneficiary.
* @param _beneficiary the address of the account receiving the grant
* @param _amount the amount (in 1/18 token) of the grant
* @param _vestingDurationInDays the vesting period of the grant in days
* @param _vestingCliffInDays the cliff period of the grant in days
*
* Emits a {GrantAdded} event indicating the beneficiary address.
*
* Requirements:
*
* - The msg.sender is the owner of the contract.
* - The beneficiary has no other Grants.
* - The given grant amount + other added grants is smaller or equal to the totalAmountOfGrants
* - The amount vested per day (amount/vestingDurationInDays) is bigger than 0.
* - The requirement described in function {calculateGrantClaim} for msg.sender.
* - The contract can transfer token on behalf of the owner of the contract.
*/
function addTokenGrant(
address _beneficiary,
uint256 _amount,
uint16 _vestingDurationInDays,
uint16 _vestingCliffInDays
) external onlyOwner {
require(tokenGrants[_beneficiary].amount == 0, "Grant already exists!");
storedAddedAmount = storedAddedAmount.add(_amount);
require(
storedAddedAmount <= totalAmountOfGrants,
"Amount exceeds grants balance!"
);
uint256 amountVestedPerDay = _amount.div(_vestingDurationInDays);
require(amountVestedPerDay > 0, "amountVestedPerDay is 0");
require(
bloXmoveToken.transferFrom(owner(), address(this), _amount),
"transferFrom Error"
);
Grant memory grant = Grant({
vestingStartTime: startTime + _vestingCliffInDays * 1 days,
amount: _amount,
vestingDuration: _vestingDurationInDays,
daysClaimed: 0,
totalClaimed: 0,
beneficiary: _beneficiary
});
tokenGrants[_beneficiary] = grant;
emit GrantAdded(_beneficiary);
}
/**
* @dev Claim the available vested tokens.
*
* This function is called by the beneficiaries to claim their vested tokens.
*
* Emits a {GrantTokensClaimed} event indicating the beneficiary address and
* the claimed amount.
*
* Requirements:
*
* - The vested amount to claim is bigger than 0
* - The requirement described in function {calculateGrantClaim} for msg.sender
* - The contract can transfer tokens to the beneficiary
*/
function claimVestedTokens() external {
uint16 daysVested;
uint256 amountVested;
(daysVested, amountVested) = calculateGrantClaim(_msgSender());
require(amountVested > 0, "Vested is 0");
Grant storage tokenGrant = tokenGrants[_msgSender()];
tokenGrant.daysClaimed = uint16(tokenGrant.daysClaimed.add(daysVested));
tokenGrant.totalClaimed = uint256(
tokenGrant.totalClaimed.add(amountVested)
);
require(
bloXmoveToken.transfer(tokenGrant.beneficiary, amountVested),
"no tokens"
);
emit GrantTokensClaimed(tokenGrant.beneficiary, amountVested);
}
/**
* @dev calculate the days and the amount vested for a particular claim.
*
* Requirements:
*
* - The Grant ist not fully claimed
* - The current time is bigger than the starttime.
*
* @return a tuple of days vested and amount of vested tokens.
*/
function calculateGrantClaim(address _beneficiary)
private
view
returns (uint16, uint256)
{
Grant storage tokenGrant = tokenGrants[_beneficiary];
require(tokenGrant.amount > 0, "no Grant");
require(
tokenGrant.totalClaimed < tokenGrant.amount,
"Grant fully claimed"
);
// Check cliffing duration
if (currentTime() < tokenGrant.vestingStartTime) {
return (0, 0);
}
uint256 elapsedDays = currentTime()
.sub(tokenGrant.vestingStartTime - 1 days)
.div(1 days);
// If over vesting duration, all tokens vested
if (elapsedDays >= tokenGrant.vestingDuration) {
// solve the uneven vest issue that could accure
uint256 remainingGrant = tokenGrant.amount.sub(
tokenGrant.totalClaimed
);
return (tokenGrant.vestingDuration, remainingGrant);
} else {
uint16 daysVested = uint16(elapsedDays.sub(tokenGrant.daysClaimed));
uint256 amountVestedPerDay = tokenGrant.amount.div(
uint256(tokenGrant.vestingDuration)
);
uint256 amountVested = uint256(daysVested.mul(amountVestedPerDay));
return (daysVested, amountVested);
}
}
/**
* @dev Get the amount of tokens that are currently available to claim for a given beneficiary.
* Reverts if there is no grant for the beneficiary.
*
* @return the amount of tokens that are currently available to claim, 0 if fully claimed.
*/
function getCurrentAmountToClaim(address _beneficiary)
public
view
returns (uint256)
{
Grant storage tokenGrant = tokenGrants[_beneficiary];
require(tokenGrant.amount > 0, "no Grant");
if (tokenGrant.totalClaimed == tokenGrant.amount) {
return 0;
}
uint256 amountVested;
(, amountVested) = calculateGrantClaim(_beneficiary);
return amountVested;
}
/**
* @dev Get the remaining grant amount for a given beneficiary.
* @return the remaining grant amount.
*/
function getRemainingGrant(address _beneficiary)
public
view
returns (uint256)
{
Grant storage tokenGrant = tokenGrants[_beneficiary];
return tokenGrant.amount.sub(tokenGrant.totalClaimed);
}
/**
* @dev Get the vesting start time for a given beneficiary.
* @return the start time.
*/
function getVestingStartTime(address _beneficiary)
public
view
returns (uint256)
{
Grant storage tokenGrant = tokenGrants[_beneficiary];
return tokenGrant.vestingStartTime;
}
/**
* @dev Get the grant amount for a given beneficiary.
* @return the grant amount.
*/
function getGrantAmount(address _beneficiary)
public
view
returns (uint256)
{
Grant storage tokenGrant = tokenGrants[_beneficiary];
return tokenGrant.amount;
}
/**
* @dev Get the timestamp from the block set by the miners.
* @return the current timestamp of the block.
*/
function currentTime() private view returns (uint256) {
return block.timestamp; // solhint-disable-line
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
} | * @dev calculate the days and the amount vested for a particular claim. Requirements: - The Grant ist not fully claimed - The current time is bigger than the starttime. @return a tuple of days vested and amount of vested tokens./ Check cliffing duration If over vesting duration, all tokens vested solve the uneven vest issue that could accure | function calculateGrantClaim(address _beneficiary)
private
view
returns (uint16, uint256)
{
Grant storage tokenGrant = tokenGrants[_beneficiary];
require(tokenGrant.amount > 0, "no Grant");
require(
tokenGrant.totalClaimed < tokenGrant.amount,
"Grant fully claimed"
);
if (currentTime() < tokenGrant.vestingStartTime) {
return (0, 0);
}
uint256 elapsedDays = currentTime()
.sub(tokenGrant.vestingStartTime - 1 days)
.div(1 days);
if (elapsedDays >= tokenGrant.vestingDuration) {
uint256 remainingGrant = tokenGrant.amount.sub(
tokenGrant.totalClaimed
);
return (tokenGrant.vestingDuration, remainingGrant);
uint16 daysVested = uint16(elapsedDays.sub(tokenGrant.daysClaimed));
uint256 amountVestedPerDay = tokenGrant.amount.div(
uint256(tokenGrant.vestingDuration)
);
uint256 amountVested = uint256(daysVested.mul(amountVestedPerDay));
return (daysVested, amountVested);
}
}
| 321,995 | [
1,
11162,
326,
4681,
471,
326,
3844,
331,
3149,
364,
279,
6826,
7516,
18,
29076,
30,
300,
1021,
19689,
19165,
486,
7418,
7516,
329,
300,
1021,
783,
813,
353,
18983,
2353,
326,
23437,
18,
327,
279,
3193,
434,
4681,
331,
3149,
471,
3844,
434,
331,
3149,
2430,
18,
19,
2073,
927,
3048,
310,
3734,
971,
1879,
331,
10100,
3734,
16,
777,
2430,
331,
3149,
12439,
326,
640,
16728,
331,
395,
5672,
716,
3377,
4078,
594,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4604,
9021,
9762,
12,
2867,
389,
70,
4009,
74,
14463,
814,
13,
203,
3639,
3238,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
2313,
16,
2254,
5034,
13,
203,
565,
288,
203,
3639,
19689,
2502,
1147,
9021,
273,
1147,
29598,
63,
67,
70,
4009,
74,
14463,
814,
15533,
203,
3639,
2583,
12,
2316,
9021,
18,
8949,
405,
374,
16,
315,
2135,
19689,
8863,
203,
3639,
2583,
12,
203,
5411,
1147,
9021,
18,
4963,
9762,
329,
411,
1147,
9021,
18,
8949,
16,
203,
5411,
315,
9021,
7418,
7516,
329,
6,
203,
3639,
11272,
203,
3639,
309,
261,
2972,
950,
1435,
411,
1147,
9021,
18,
90,
10100,
13649,
13,
288,
203,
5411,
327,
261,
20,
16,
374,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
9613,
9384,
273,
6680,
1435,
203,
5411,
263,
1717,
12,
2316,
9021,
18,
90,
10100,
13649,
300,
404,
4681,
13,
203,
5411,
263,
2892,
12,
21,
4681,
1769,
203,
203,
3639,
309,
261,
26201,
9384,
1545,
1147,
9021,
18,
90,
10100,
5326,
13,
288,
203,
5411,
2254,
5034,
4463,
9021,
273,
1147,
9021,
18,
8949,
18,
1717,
12,
203,
7734,
1147,
9021,
18,
4963,
9762,
329,
203,
5411,
11272,
203,
5411,
327,
261,
2316,
9021,
18,
90,
10100,
5326,
16,
4463,
9021,
1769,
203,
5411,
2254,
2313,
4681,
58,
3149,
273,
2254,
2313,
12,
26201,
9384,
18,
1717,
12,
2316,
9021,
18,
9810,
9762,
329,
10019,
203,
5411,
2254,
5034,
3844,
58,
3149,
2173,
4245,
273,
1147,
9021,
18,
8949,
18,
2892,
12,
203,
7734,
2254,
5034,
12,
2
] |
./partial_match/4/0xF8d0a3F8a21e9f57394e4C63e9bB4212FAae9Da5/sources/Boardroom.sol | ======== discount ==============*/ | function withdrawWithDiscount(uint256 amount, address gasSponsor, uint256 flag)
external
discountGas(gasSponsor, flag)
{
withdrawInternal(amount);
}
| 8,584,345 | [
1,
1432,
12137,
422,
14468,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
1190,
9866,
12,
11890,
5034,
3844,
16,
1758,
16189,
55,
500,
2467,
16,
2254,
5034,
2982,
13,
7010,
3639,
3903,
7010,
3639,
12137,
27998,
12,
31604,
55,
500,
2467,
16,
2982,
13,
203,
565,
288,
203,
3639,
598,
9446,
3061,
12,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/421613/0xC7475E940ed80773703a783F0eF4858c850FD877/sources/project_/contracts/VestedERC20.sol | @title VestedERC20 @author zefram.eth @notice An ERC20 wrapper token that linearly vests an underlying token to its holders | contract VestedERC20 is ERC20 {
using SafeTransferLib for SolmateERC20;
error Error_Wrap_VestOver();
error Error_Wrap_AmountTooLarge();
mapping(address => uint256) public claimedUnderlyingAmount;
import {ERC20 as SolmateERC20} from "solmate/src/tokens/ERC20.sol";
import {SafeTransferLib} from "solmate/src/utils/SafeTransferLib.sol";
import {ERC20} from "./lib/ERC20_.sol";
import {FullMath} from "./lib/FullMath.sol";
function underlying() public pure returns (address _underlying) {
return _getArgAddress(0x41);
}
function startTimestamp() public pure returns (uint64 _startTimestamp) {
return _getArgUint64(0x55);
}
function endTimestamp() public pure returns (uint64 _endTimestamp) {
return _getArgUint64(0x5d);
}
function wrap(uint256 underlyingAmount, address recipient)
external
returns (uint256 wrappedTokenAmount)
{
uint256 _startTimestamp = startTimestamp();
uint256 _endTimestamp = endTimestamp();
if (block.timestamp >= _endTimestamp) {
revert Error_Wrap_VestOver();
}
if (
underlyingAmount >=
type(uint256).max / (_endTimestamp - _startTimestamp)
) {
revert Error_Wrap_AmountTooLarge();
}
if (block.timestamp >= _startTimestamp) {
wrappedTokenAmount =
(underlyingAmount * (_endTimestamp - _startTimestamp)) /
(_endTimestamp - block.timestamp);
claimedUnderlyingAmount[recipient] +=
wrappedTokenAmount -
underlyingAmount;
wrappedTokenAmount = underlyingAmount;
}
SolmateERC20 underlyingToken = SolmateERC20(underlying());
underlyingToken.safeTransferFrom(
msg.sender,
address(this),
underlyingAmount
);
}
function wrap(uint256 underlyingAmount, address recipient)
external
returns (uint256 wrappedTokenAmount)
{
uint256 _startTimestamp = startTimestamp();
uint256 _endTimestamp = endTimestamp();
if (block.timestamp >= _endTimestamp) {
revert Error_Wrap_VestOver();
}
if (
underlyingAmount >=
type(uint256).max / (_endTimestamp - _startTimestamp)
) {
revert Error_Wrap_AmountTooLarge();
}
if (block.timestamp >= _startTimestamp) {
wrappedTokenAmount =
(underlyingAmount * (_endTimestamp - _startTimestamp)) /
(_endTimestamp - block.timestamp);
claimedUnderlyingAmount[recipient] +=
wrappedTokenAmount -
underlyingAmount;
wrappedTokenAmount = underlyingAmount;
}
SolmateERC20 underlyingToken = SolmateERC20(underlying());
underlyingToken.safeTransferFrom(
msg.sender,
address(this),
underlyingAmount
);
}
function wrap(uint256 underlyingAmount, address recipient)
external
returns (uint256 wrappedTokenAmount)
{
uint256 _startTimestamp = startTimestamp();
uint256 _endTimestamp = endTimestamp();
if (block.timestamp >= _endTimestamp) {
revert Error_Wrap_VestOver();
}
if (
underlyingAmount >=
type(uint256).max / (_endTimestamp - _startTimestamp)
) {
revert Error_Wrap_AmountTooLarge();
}
if (block.timestamp >= _startTimestamp) {
wrappedTokenAmount =
(underlyingAmount * (_endTimestamp - _startTimestamp)) /
(_endTimestamp - block.timestamp);
claimedUnderlyingAmount[recipient] +=
wrappedTokenAmount -
underlyingAmount;
wrappedTokenAmount = underlyingAmount;
}
SolmateERC20 underlyingToken = SolmateERC20(underlying());
underlyingToken.safeTransferFrom(
msg.sender,
address(this),
underlyingAmount
);
}
function wrap(uint256 underlyingAmount, address recipient)
external
returns (uint256 wrappedTokenAmount)
{
uint256 _startTimestamp = startTimestamp();
uint256 _endTimestamp = endTimestamp();
if (block.timestamp >= _endTimestamp) {
revert Error_Wrap_VestOver();
}
if (
underlyingAmount >=
type(uint256).max / (_endTimestamp - _startTimestamp)
) {
revert Error_Wrap_AmountTooLarge();
}
if (block.timestamp >= _startTimestamp) {
wrappedTokenAmount =
(underlyingAmount * (_endTimestamp - _startTimestamp)) /
(_endTimestamp - block.timestamp);
claimedUnderlyingAmount[recipient] +=
wrappedTokenAmount -
underlyingAmount;
wrappedTokenAmount = underlyingAmount;
}
SolmateERC20 underlyingToken = SolmateERC20(underlying());
underlyingToken.safeTransferFrom(
msg.sender,
address(this),
underlyingAmount
);
}
} else {
_mint(recipient, wrappedTokenAmount);
function redeem(address recipient)
external
returns (uint256 redeemedAmount)
{
uint256 _claimedUnderlyingAmount = claimedUnderlyingAmount[msg.sender];
redeemedAmount = _getRedeemableAmount(
msg.sender,
_claimedUnderlyingAmount
);
claimedUnderlyingAmount[msg.sender] =
_claimedUnderlyingAmount +
redeemedAmount;
if (redeemedAmount > 0) {
SolmateERC20 underlyingToken = SolmateERC20(underlying());
underlyingToken.safeTransfer(recipient, redeemedAmount);
}
}
function redeem(address recipient)
external
returns (uint256 redeemedAmount)
{
uint256 _claimedUnderlyingAmount = claimedUnderlyingAmount[msg.sender];
redeemedAmount = _getRedeemableAmount(
msg.sender,
_claimedUnderlyingAmount
);
claimedUnderlyingAmount[msg.sender] =
_claimedUnderlyingAmount +
redeemedAmount;
if (redeemedAmount > 0) {
SolmateERC20 underlyingToken = SolmateERC20(underlying());
underlyingToken.safeTransfer(recipient, redeemedAmount);
}
}
function transfer(address to, uint256 amount)
public
override
returns (bool)
{
uint256 senderBalance = balanceOf[msg.sender];
uint256 senderClaimedUnderlyingAmount = claimedUnderlyingAmount[
msg.sender
];
balanceOf[msg.sender] = senderBalance - amount;
unchecked {
balanceOf[to] += amount;
}
uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv(
senderClaimedUnderlyingAmount,
amount,
senderBalance
);
if (claimedUnderlyingAmountToTransfer > 0) {
claimedUnderlyingAmount[msg.sender] =
senderClaimedUnderlyingAmount -
claimedUnderlyingAmountToTransfer;
unchecked {
claimedUnderlyingAmount[
to
] += claimedUnderlyingAmountToTransfer;
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transfer(address to, uint256 amount)
public
override
returns (bool)
{
uint256 senderBalance = balanceOf[msg.sender];
uint256 senderClaimedUnderlyingAmount = claimedUnderlyingAmount[
msg.sender
];
balanceOf[msg.sender] = senderBalance - amount;
unchecked {
balanceOf[to] += amount;
}
uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv(
senderClaimedUnderlyingAmount,
amount,
senderBalance
);
if (claimedUnderlyingAmountToTransfer > 0) {
claimedUnderlyingAmount[msg.sender] =
senderClaimedUnderlyingAmount -
claimedUnderlyingAmountToTransfer;
unchecked {
claimedUnderlyingAmount[
to
] += claimedUnderlyingAmountToTransfer;
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transfer(address to, uint256 amount)
public
override
returns (bool)
{
uint256 senderBalance = balanceOf[msg.sender];
uint256 senderClaimedUnderlyingAmount = claimedUnderlyingAmount[
msg.sender
];
balanceOf[msg.sender] = senderBalance - amount;
unchecked {
balanceOf[to] += amount;
}
uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv(
senderClaimedUnderlyingAmount,
amount,
senderBalance
);
if (claimedUnderlyingAmountToTransfer > 0) {
claimedUnderlyingAmount[msg.sender] =
senderClaimedUnderlyingAmount -
claimedUnderlyingAmountToTransfer;
unchecked {
claimedUnderlyingAmount[
to
] += claimedUnderlyingAmountToTransfer;
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transfer(address to, uint256 amount)
public
override
returns (bool)
{
uint256 senderBalance = balanceOf[msg.sender];
uint256 senderClaimedUnderlyingAmount = claimedUnderlyingAmount[
msg.sender
];
balanceOf[msg.sender] = senderBalance - amount;
unchecked {
balanceOf[to] += amount;
}
uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv(
senderClaimedUnderlyingAmount,
amount,
senderBalance
);
if (claimedUnderlyingAmountToTransfer > 0) {
claimedUnderlyingAmount[msg.sender] =
senderClaimedUnderlyingAmount -
claimedUnderlyingAmountToTransfer;
unchecked {
claimedUnderlyingAmount[
to
] += claimedUnderlyingAmountToTransfer;
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public override returns (bool) {
if (allowed != type(uint256).max)
allowance[from][msg.sender] = allowed - amount;
uint256 fromBalance = balanceOf[from];
uint256 fromClaimedUnderlyingAmount = claimedUnderlyingAmount[from];
balanceOf[from] = fromBalance - amount;
unchecked {
balanceOf[to] += amount;
}
uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv(
fromClaimedUnderlyingAmount,
amount,
fromBalance
);
if (claimedUnderlyingAmountToTransfer > 0) {
claimedUnderlyingAmount[from] =
fromClaimedUnderlyingAmount -
claimedUnderlyingAmountToTransfer;
unchecked {
claimedUnderlyingAmount[
to
] += claimedUnderlyingAmountToTransfer;
}
}
emit Transfer(from, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public override returns (bool) {
if (allowed != type(uint256).max)
allowance[from][msg.sender] = allowed - amount;
uint256 fromBalance = balanceOf[from];
uint256 fromClaimedUnderlyingAmount = claimedUnderlyingAmount[from];
balanceOf[from] = fromBalance - amount;
unchecked {
balanceOf[to] += amount;
}
uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv(
fromClaimedUnderlyingAmount,
amount,
fromBalance
);
if (claimedUnderlyingAmountToTransfer > 0) {
claimedUnderlyingAmount[from] =
fromClaimedUnderlyingAmount -
claimedUnderlyingAmountToTransfer;
unchecked {
claimedUnderlyingAmount[
to
] += claimedUnderlyingAmountToTransfer;
}
}
emit Transfer(from, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public override returns (bool) {
if (allowed != type(uint256).max)
allowance[from][msg.sender] = allowed - amount;
uint256 fromBalance = balanceOf[from];
uint256 fromClaimedUnderlyingAmount = claimedUnderlyingAmount[from];
balanceOf[from] = fromBalance - amount;
unchecked {
balanceOf[to] += amount;
}
uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv(
fromClaimedUnderlyingAmount,
amount,
fromBalance
);
if (claimedUnderlyingAmountToTransfer > 0) {
claimedUnderlyingAmount[from] =
fromClaimedUnderlyingAmount -
claimedUnderlyingAmountToTransfer;
unchecked {
claimedUnderlyingAmount[
to
] += claimedUnderlyingAmountToTransfer;
}
}
emit Transfer(from, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public override returns (bool) {
if (allowed != type(uint256).max)
allowance[from][msg.sender] = allowed - amount;
uint256 fromBalance = balanceOf[from];
uint256 fromClaimedUnderlyingAmount = claimedUnderlyingAmount[from];
balanceOf[from] = fromBalance - amount;
unchecked {
balanceOf[to] += amount;
}
uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv(
fromClaimedUnderlyingAmount,
amount,
fromBalance
);
if (claimedUnderlyingAmountToTransfer > 0) {
claimedUnderlyingAmount[from] =
fromClaimedUnderlyingAmount -
claimedUnderlyingAmountToTransfer;
unchecked {
claimedUnderlyingAmount[
to
] += claimedUnderlyingAmountToTransfer;
}
}
emit Transfer(from, to, amount);
return true;
}
function getRedeemableAmount(address holder)
external
view
returns (uint256)
{
return _getRedeemableAmount(holder, claimedUnderlyingAmount[holder]);
}
function _getRedeemableAmount(
address holder,
uint256 holderClaimedUnderlyingAmount
) internal view returns (uint256) {
uint256 _startTimestamp = startTimestamp();
uint256 _endTimestamp = endTimestamp();
if (block.timestamp <= _startTimestamp) {
return 0;
return balanceOf[holder] - holderClaimedUnderlyingAmount;
return
(balanceOf[holder] * (block.timestamp - _startTimestamp)) /
(_endTimestamp - _startTimestamp) -
holderClaimedUnderlyingAmount;
}
}
function _getRedeemableAmount(
address holder,
uint256 holderClaimedUnderlyingAmount
) internal view returns (uint256) {
uint256 _startTimestamp = startTimestamp();
uint256 _endTimestamp = endTimestamp();
if (block.timestamp <= _startTimestamp) {
return 0;
return balanceOf[holder] - holderClaimedUnderlyingAmount;
return
(balanceOf[holder] * (block.timestamp - _startTimestamp)) /
(_endTimestamp - _startTimestamp) -
holderClaimedUnderlyingAmount;
}
}
} else if (block.timestamp >= _endTimestamp) {
} else {
} | 11,567,907 | [
1,
58,
3149,
654,
39,
3462,
225,
998,
10241,
1940,
18,
546,
225,
1922,
4232,
39,
3462,
4053,
1147,
716,
9103,
715,
331,
25563,
392,
6808,
1147,
358,
2097,
366,
4665,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
776,
3149,
654,
39,
3462,
353,
4232,
39,
3462,
288,
203,
203,
565,
1450,
14060,
5912,
5664,
364,
348,
355,
81,
340,
654,
39,
3462,
31,
203,
203,
203,
565,
555,
1068,
67,
2964,
67,
58,
395,
4851,
5621,
203,
565,
555,
1068,
67,
2964,
67,
6275,
10703,
20020,
5621,
203,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
7516,
329,
14655,
6291,
6275,
31,
203,
203,
203,
203,
5666,
288,
654,
39,
3462,
487,
348,
355,
81,
340,
654,
39,
3462,
97,
628,
315,
18281,
81,
340,
19,
4816,
19,
7860,
19,
654,
39,
3462,
18,
18281,
14432,
203,
5666,
288,
9890,
5912,
5664,
97,
628,
315,
18281,
81,
340,
19,
4816,
19,
5471,
19,
9890,
5912,
5664,
18,
18281,
14432,
203,
5666,
288,
654,
39,
3462,
97,
628,
25165,
2941,
19,
654,
39,
3462,
27799,
18281,
14432,
203,
5666,
288,
5080,
10477,
97,
628,
25165,
2941,
19,
5080,
10477,
18,
18281,
14432,
203,
565,
445,
6808,
1435,
1071,
16618,
1135,
261,
2867,
389,
9341,
6291,
13,
288,
203,
3639,
327,
389,
588,
4117,
1887,
12,
20,
92,
9803,
1769,
203,
565,
289,
203,
203,
565,
445,
787,
4921,
1435,
1071,
16618,
1135,
261,
11890,
1105,
389,
1937,
4921,
13,
288,
203,
3639,
327,
389,
588,
4117,
5487,
1105,
12,
20,
92,
2539,
1769,
203,
565,
289,
203,
203,
565,
445,
679,
4921,
1435,
1071,
16618,
1135,
261,
11890,
1105,
389,
409,
4921,
13,
288,
203,
3639,
327,
389,
588,
4117,
5487,
1105,
12,
20,
92,
25,
72,
1769,
2
] |
./partial_match/4/0xD68f4CAE482452ad9986183C10CF17AD5734efE5/sources/contracts/Component.sol | Set project address. | function setProjectAddress (address _newAddr) public onlyOwner {
projectAddress = _newAddr;
}
| 8,762,292 | [
1,
694,
1984,
1758,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
25323,
1887,
261,
2867,
389,
2704,
3178,
13,
1071,
1338,
5541,
288,
203,
3639,
1984,
1887,
273,
389,
2704,
3178,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
* Code yanked from https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
uint8 public decimals;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract DAIHardFactory {
using SafeMath for uint;
event NewTrade(uint id, address tradeAddress, bool indexed initiatorIsCustodian);
ERC20Interface public daiContract;
address public founderFeeAddress;
constructor(ERC20Interface _daiContract, address _founderFeeAddress)
public {
daiContract = _daiContract;
founderFeeAddress = _founderFeeAddress;
}
struct CreationInfo {
address address_;
uint blocknum;
}
CreationInfo[] public createdTrades;
function getFounderFee(uint tradeAmount)
public
pure
returns (uint founderFee) {
return tradeAmount / 200;
}
/*
The Solidity compiler can't handle much stack depth,
so we have to pack some args together in annoying ways...
Hence 'uintArgs' and 'addressArgs'.
Here are the layouts for createOpenTrade:
uintArgs:
0 - tradeAmount
1 - beneficiaryDeposit
2 - abortPunishment
3 - pokeReward
4 - autorecallInterval
5 - autoabortInterval
6 - autoreleaseInterval
7 - devFee
addressArgs:
0 - initiator
1 - devFeeAddress
*/
function createOpenTrade(address[2] calldata addressArgs,
bool initiatorIsCustodian,
uint[8] calldata uintArgs,
string calldata terms,
string calldata _commPubkey
)
external
returns (DAIHardTrade) {
uint initialTransfer;
uint[8] memory newUintArgs; // Note that this structure is not the same as the above comment describes. See below in DAIHardTrade.open.
if (initiatorIsCustodian) {
initialTransfer = uintArgs[0].add(uintArgs[3]).add(getFounderFee(uintArgs[0])).add(uintArgs[7]);
// tradeAmount + pokeReward + getFounderFee(tradeAmount) + devFee
newUintArgs = [uintArgs[1], uintArgs[2], uintArgs[3], uintArgs[4], uintArgs[5], uintArgs[6], getFounderFee(uintArgs[0]), uintArgs[7]];
// see uintArgs comment above DAIHardTrade.beginInOpenPhase
}
else {
initialTransfer = uintArgs[1].add(uintArgs[3]).add(getFounderFee(uintArgs[0])).add(uintArgs[7]);
// beneficiaryDeposit + pokeReward + getFounderFee(tradeAmount) + devFee
newUintArgs = [uintArgs[0], uintArgs[2], uintArgs[3], uintArgs[4], uintArgs[5], uintArgs[6], getFounderFee(uintArgs[0]), uintArgs[7]];
// see uintArgs comment above DAIHardTrade.beginInOpenPhase
}
// Create the new trade and add its creationInfo to createdTrades, and emit an event.
// This provides a DAIHard interface two options to find all created trades:
// scan for NewTrade events or read the createdTrades array.
DAIHardTrade newTrade = new DAIHardTrade(daiContract, founderFeeAddress, addressArgs[1]);
createdTrades.push(CreationInfo(address(newTrade), block.number));
emit NewTrade(createdTrades.length - 1, address(newTrade), initiatorIsCustodian);
// transfer DAI to the trade and open it
require(daiContract.transferFrom(msg.sender, address(newTrade), initialTransfer),
"Token transfer failed. Did you call approve() on the DAI contract?"
);
newTrade.beginInOpenPhase(addressArgs[0], initiatorIsCustodian, newUintArgs, terms, _commPubkey);
return newTrade;
}
/*
Array layouts for createCommittedTrade:
uintArgs:
0 - tradeAmount
1 - beneficiaryDeposit
2 - abortPunishment
3 - pokeReward
4 - autoabortInterval
5 - autoreleaseInterval
6 - devFee
addressArgs:
0 - custodian
1 - beneficiary
2 - devFeeAddress
*/
function createCommittedTrade(address[3] calldata addressArgs,
bool initiatorIsCustodian,
uint[7] calldata uintArgs,
string calldata _terms,
string calldata _initiatorCommPubkey,
string calldata _responderCommPubkey
)
external
returns (DAIHardTrade) {
uint initialTransfer = uintArgs[0].add(uintArgs[1]).add(uintArgs[3]).add(getFounderFee(uintArgs[0]).add(uintArgs[6]));
// initialTransfer = tradeAmount + beneficiaryDeposit + pokeReward + getFounderFee(tradeAmount) + devFee
uint[7] memory newUintArgs = [uintArgs[1], uintArgs[2], uintArgs[3], uintArgs[4], uintArgs[5], getFounderFee(uintArgs[0]), uintArgs[6]];
// see uintArgs comment above DAIHardTrade.beginInCommittedPhase
DAIHardTrade newTrade = new DAIHardTrade(daiContract, founderFeeAddress, addressArgs[2]);
createdTrades.push(CreationInfo(address(newTrade), block.number));
emit NewTrade(createdTrades.length - 1, address(newTrade), initiatorIsCustodian);
require(daiContract.transferFrom(msg.sender, address(newTrade), initialTransfer),
"Token transfer failed. Did you call approve() on the DAI contract?"
);
newTrade.beginInCommittedPhase(addressArgs[0],
addressArgs[1],
initiatorIsCustodian,
newUintArgs,
_terms,
_initiatorCommPubkey,
_responderCommPubkey
);
return newTrade;
}
function numTrades()
external
view
returns (uint num) {
return createdTrades.length;
}
}
contract DAIHardTrade {
using SafeMath for uint;
enum Phase {Creating, Open, Committed, Judgment, Closed}
Phase public phase;
modifier inPhase(Phase p) {
require(phase == p, "inPhase check failed.");
_;
}
enum ClosedReason {NotClosed, Recalled, Aborted, Released, Burned}
ClosedReason public closedReason;
uint[5] public phaseStartTimestamps;
uint[5] public phaseStartBlocknums;
function changePhase(Phase p)
internal {
phase = p;
phaseStartTimestamps[uint(p)] = block.timestamp;
phaseStartBlocknums[uint(p)] = block.number;
}
address public initiator;
address public responder;
// The contract only has two parties, but depending on how it's opened,
// the initiator for example might be either the custodian OR the beneficiary,
// so we need four 'role' variables to capture each possible combination.
bool public initiatorIsCustodian;
address public custodian;
address public beneficiary;
modifier onlyInitiator() {
require(msg.sender == initiator, "msg.sender is not Initiator.");
_;
}
modifier onlyResponder() {
require(msg.sender == responder, "msg.sender is not Responder.");
_;
}
modifier onlyCustodian() {
require (msg.sender == custodian, "msg.sender is not Custodian.");
_;
}
modifier onlyBeneficiary() {
require (msg.sender == beneficiary, "msg.sender is not Beneficiary.");
_;
}
modifier onlyContractParty() { // Must be one of the two parties involved in the contract
// Note this still covers the case in which responder still is 0x0, as msg.sender can never be 0x0,
// in which case this will revert if msg.sender != initiator.
require(msg.sender == initiator || msg.sender == responder, "msg.sender is not a party in this contract.");
_;
}
ERC20Interface public daiContract;
address public founderFeeAddress;
address public devFeeAddress;
bool public pokeRewardGranted;
constructor(ERC20Interface _daiContract, address _founderFeeAddress, address _devFeeAddress)
public {
// If gas was not an issue we would leave the next three lines in for explicit clarity,
// but technically they are a waste of gas, because we're simply setting them to the null values
// (which happens automatically anyway when the contract is instantiated)
// changePhase(Phase.Creating);
// closedReason = ClosedReason.NotClosed;
// pokeRewardGranted = false;
daiContract = _daiContract;
founderFeeAddress = _founderFeeAddress;
devFeeAddress = _devFeeAddress;
}
uint public tradeAmount;
uint public beneficiaryDeposit;
uint public abortPunishment;
uint public autorecallInterval;
uint public autoabortInterval;
uint public autoreleaseInterval;
uint public pokeReward;
uint public founderFee;
uint public devFee;
/* ---------------------- CREATING PHASE -----------------------
The only reason for this phase is so the Factory can have somewhere
to send the DAI before the Trade is truly initiated in the Opened phase.
This way the trade can take into account its balance
when setting its initial Open-phase state.
The Factory creates the DAIHardTrade and moves it past this state in a single call,
so any DAIHardTrade made by the factory should never be "seen" in this state
(the DH interface ignores trades not created by the Factory contract).
------------------------------------------------------------ */
event Initiated(string terms, string commPubkey);
/*
uintArgs:
0 - responderDeposit
1 - abortPunishment
2 - pokeReward
3 - autorecallInterval
4 - autoabortInterval
5 - autoreleaseInterval
6 - founderFee
7 - devFee
*/
function beginInOpenPhase(address _initiator,
bool _initiatorIsCustodian,
uint[8] memory uintArgs,
string memory terms,
string memory commPubkey
)
public
inPhase(Phase.Creating)
/* any msg.sender */ {
uint responderDeposit = uintArgs[0];
abortPunishment = uintArgs[1];
pokeReward = uintArgs[2];
autorecallInterval = uintArgs[3];
autoabortInterval = uintArgs[4];
autoreleaseInterval = uintArgs[5];
founderFee = uintArgs[6];
devFee = uintArgs[7];
initiator = _initiator;
initiatorIsCustodian = _initiatorIsCustodian;
if (initiatorIsCustodian) {
custodian = initiator;
tradeAmount = getBalance().sub(pokeReward.add(founderFee).add(devFee));
beneficiaryDeposit = responderDeposit;
}
else {
beneficiary = initiator;
tradeAmount = responderDeposit;
beneficiaryDeposit = getBalance().sub(pokeReward.add(founderFee).add(devFee));
}
require(beneficiaryDeposit <= tradeAmount, "A beneficiaryDeposit greater than tradeAmount is not allowed.");
require(abortPunishment <= beneficiaryDeposit, "An abortPunishment greater than beneficiaryDeposit is not allowed.");
changePhase(Phase.Open);
emit Initiated(terms, commPubkey);
}
/*
uintArgs:
0 - beneficiaryDeposit
1 - abortPunishment
2 - pokeReward
3 - autoabortInterval
4 - autoreleaseInterval
5 - founderFee
6 - devFee
*/
function beginInCommittedPhase(address _custodian,
address _beneficiary,
bool _initiatorIsCustodian,
uint[7] memory uintArgs,
string memory terms,
string memory initiatorCommPubkey,
string memory responderCommPubkey
)
public
inPhase(Phase.Creating)
/* any msg.sender */{
beneficiaryDeposit = uintArgs[0];
abortPunishment = uintArgs[1];
pokeReward = uintArgs[2];
autoabortInterval = uintArgs[3];
autoreleaseInterval = uintArgs[4];
founderFee = uintArgs[5];
devFee = uintArgs[6];
custodian = _custodian;
beneficiary = _beneficiary;
initiatorIsCustodian = _initiatorIsCustodian;
if (initiatorIsCustodian) {
initiator = custodian;
responder = beneficiary;
}
else {
initiator = beneficiary;
responder = custodian;
}
tradeAmount = getBalance().sub(beneficiaryDeposit.add(pokeReward).add(founderFee).add(devFee));
require(beneficiaryDeposit <= tradeAmount, "A beneficiaryDeposit greater than tradeAmount is not allowed.");
require(abortPunishment <= beneficiaryDeposit, "An abortPunishment greater than beneficiaryDeposit is not allowed.");
changePhase(Phase.Committed);
emit Initiated(terms, initiatorCommPubkey);
emit Committed(responder, responderCommPubkey);
}
/* ---------------------- OPEN PHASE --------------------------
In the Open phase, the Initiator (who may be the Custodian or the Beneficiary)
waits for a Responder (who will claim the remaining role).
We move to the Commited phase once someone becomes the Responder by executing commit(),
which requires a successful withdraw of tokens from msg.sender of getResponderDeposit
(either tradeAmount or beneficiaryDeposit, depending on the role of the responder).
At any time in this phase, the Initiator can cancel the whole thing by calling recall().
This returns the trade's entire balance including fees to the Initiator.
After autorecallInterval has passed, the only state change allowed is to recall,
which at that point can be triggered by anyone via poke().
------------------------------------------------------------ */
event Recalled();
event Committed(address responder, string commPubkey);
function recall()
external
inPhase(Phase.Open)
onlyInitiator() {
internalRecall();
}
function internalRecall()
internal {
changePhase(Phase.Closed);
closedReason = ClosedReason.Recalled;
emit Recalled();
require(daiContract.transfer(initiator, getBalance()), "Recall of DAI to initiator failed!");
// Note that this will also return the founderFee and devFee to the intiator,
// as well as the pokeReward if it hasn't yet been sent.
}
function autorecallAvailable()
public
view
inPhase(Phase.Open)
returns(bool available) {
return (block.timestamp >= phaseStartTimestamps[uint(Phase.Open)].add(autorecallInterval));
}
function commit(address _responder, string calldata commPubkey)
external
inPhase(Phase.Open)
/* any msg.sender */ {
require(!autorecallAvailable(), "autorecallInterval has passed; this offer has expired.");
responder = _responder;
if (initiatorIsCustodian) {
beneficiary = responder;
}
else {
custodian = responder;
}
changePhase(Phase.Committed);
emit Committed(responder, commPubkey);
require(daiContract.transferFrom(msg.sender, address(this), getResponderDeposit()),
"Can't transfer the required deposit from the DAI contract. Did you call approve first?"
);
}
/* ---------------------- COMMITTED PHASE ---------------------
In the Committed phase, the Beneficiary is expected to deposit fiat for the DAI,
then call claim().
Otherwise, the Beneficiary can call abort(), which cancels the contract,
incurs a small penalty on both parties, and returns the remainder to each party.
After autoabortInterval has passed, the only state change allowed is to abort,
which can be triggered by anyone via poke().
------------------------------------------------------------ */
event Claimed();
event Aborted();
function abort()
external
inPhase(Phase.Committed)
onlyBeneficiary() {
internalAbort();
}
function internalAbort()
internal {
changePhase(Phase.Closed);
closedReason = ClosedReason.Aborted;
emit Aborted();
// Punish both parties equally by burning abortPunishment.
// Instead of burning abortPunishment twice, just burn it all in one call (saves gas).
require(daiContract.transfer(address(0x0), abortPunishment*2), "Token burn failed!");
// Security note: The above line risks overflow, but only if abortPunishment >= (maxUint/2).
// This should never happen, as abortPunishment <= beneficiaryDeposit <= tradeAmount (as required in both beginIn*Phase functions),
// which is ultimately limited by the amount of DAI the user deposited (which must be far less than maxUint/2).
// See the note below about avoiding assert() or require() to test this.
// Send back deposits minus burned amounts.
require(daiContract.transfer(beneficiary, beneficiaryDeposit.sub(abortPunishment)), "Token transfer to Beneficiary failed!");
require(daiContract.transfer(custodian, tradeAmount.sub(abortPunishment)), "Token transfer to Custodian failed!");
// Refund to initiator should include founderFee and devFee
uint sendBackToInitiator = founderFee.add(devFee);
// If there was a pokeReward left, it should also be sent back to the initiator
if (!pokeRewardGranted) {
sendBackToInitiator = sendBackToInitiator.add(pokeReward);
}
require(daiContract.transfer(initiator, sendBackToInitiator), "Token refund of founderFee+devFee+pokeReward to Initiator failed!");
}
function autoabortAvailable()
public
view
inPhase(Phase.Committed)
returns(bool passed) {
return (block.timestamp >= phaseStartTimestamps[uint(Phase.Committed)].add(autoabortInterval));
}
function claim()
external
inPhase(Phase.Committed)
onlyBeneficiary() {
require(!autoabortAvailable(), "The deposit deadline has passed!");
changePhase(Phase.Judgment);
emit Claimed();
}
/* ---------------------- CLAIMED PHASE -----------------------
In the Judgment phase, the Custodian can call release() or burn(),
and is expected to call burn() only if the Beneficiary did meet the terms
described in the 'terms' value logged with the Initiated event.
After autoreleaseInterval has passed, the only state change allowed is to release,
which can be triggered by anyone via poke().
In the case of a burn, all fees are burned as well.
------------------------------------------------------------ */
event Released();
event Burned();
function release()
external
inPhase(Phase.Judgment)
onlyCustodian() {
internalRelease();
}
function internalRelease()
internal {
changePhase(Phase.Closed);
closedReason = ClosedReason.Released;
emit Released();
//If the pokeReward has not been sent, refund it to the initiator
if (!pokeRewardGranted) {
require(daiContract.transfer(initiator, pokeReward), "Refund of pokeReward to Initiator failed!");
}
// Upon successful resolution of trade, the founderFee is sent to the founders of DAIHard,
// and the devFee is sent to wherever the original Factory creation call specified.
require(daiContract.transfer(founderFeeAddress, founderFee), "Token transfer to founderFeeAddress failed!");
require(daiContract.transfer(devFeeAddress, devFee), "Token transfer to devFeeAddress failed!");
//Release the remaining balance to the beneficiary.
require(daiContract.transfer(beneficiary, getBalance()), "Final release transfer to beneficiary failed!");
}
function autoreleaseAvailable()
public
view
inPhase(Phase.Judgment)
returns(bool available) {
return (block.timestamp >= phaseStartTimestamps[uint(Phase.Judgment)].add(autoreleaseInterval));
}
function burn()
external
inPhase(Phase.Judgment)
onlyCustodian() {
require(!autoreleaseAvailable(), "autorelease has passed; you can no longer call burn.");
internalBurn();
}
function internalBurn()
internal {
changePhase(Phase.Closed);
closedReason = ClosedReason.Burned;
emit Burned();
require(daiContract.transfer(address(0x0), getBalance()), "Final DAI burn failed!");
// Note that this also burns founderFee and devFee.
}
/* ---------------------- ANY-PHASE METHODS ----------------------- */
/*
If the contract is due for some auto___ phase transition,
anyone can call the poke() function to trigger this transition,
and the caller will be rewarded with pokeReward.
*/
event Poke();
function pokeNeeded()
public
view
/* any phase */
/* any msg.sender */
returns (bool needed) {
return ( (phase == Phase.Open && autorecallAvailable() )
|| (phase == Phase.Committed && autoabortAvailable() )
|| (phase == Phase.Judgment && autoreleaseAvailable())
);
}
function grantPokeRewardToSender()
internal {
require(!pokeRewardGranted, "The poke reward has already been sent!"); // Extra protection against re-entrancy
pokeRewardGranted = true;
daiContract.transfer(msg.sender, pokeReward);
}
function poke()
external
/* any phase */
/* any msg.sender */
returns (bool moved) {
if (phase == Phase.Open && autorecallAvailable()) {
grantPokeRewardToSender();
emit Poke();
internalRecall();
return true;
}
else if (phase == Phase.Committed && autoabortAvailable()) {
grantPokeRewardToSender();
emit Poke();
internalAbort();
return true;
}
else if (phase == Phase.Judgment && autoreleaseAvailable()) {
grantPokeRewardToSender();
emit Poke();
internalRelease();
return true;
}
else return false;
}
/*
StatementLogs allow a starting point for any necessary communication,
and can be used anytime (even in the Closed phase).
*/
event InitiatorStatementLog(string statement);
event ResponderStatementLog(string statement);
function initiatorStatement(string memory statement)
public
/* any phase */
onlyInitiator() {
emit InitiatorStatementLog(statement);
}
function responderStatement(string memory statement)
public
/* any phase */
onlyResponder() {
emit ResponderStatementLog(statement);
}
/* ---------------------- ANY-PHASE GETTERS ----------------------- */
function getResponderDeposit()
public
view
/* any phase */
/* any msg.sender */
returns(uint responderDeposit) {
if (initiatorIsCustodian) {
return beneficiaryDeposit;
}
else {
return tradeAmount;
}
}
function getState()
external
view
/* any phase */
/* any msg.sender */
returns(uint balance, Phase phase, uint phaseStartTimestamp, address responder, ClosedReason closedReason) {
return (getBalance(), this.phase(), phaseStartTimestamps[uint(this.phase())], this.responder(), this.closedReason());
}
function getBalance()
public
view
/* any phase */
/* any msg.sender */
returns(uint) {
return daiContract.balanceOf(address(this));
}
function getParameters()
external
view
/* any phase */
/* any msg.sender */
returns (address initiator,
bool initiatorIsCustodian,
uint tradeAmount,
uint beneficiaryDeposit,
uint abortPunishment,
uint autorecallInterval,
uint autoabortInterval,
uint autoreleaseInterval,
uint pokeReward
)
{
return (this.initiator(),
this.initiatorIsCustodian(),
this.tradeAmount(),
this.beneficiaryDeposit(),
this.abortPunishment(),
this.autorecallInterval(),
this.autoabortInterval(),
this.autoreleaseInterval(),
this.pokeReward()
);
}
function getPhaseStartInfo()
external
view
/* any phase */
/* any msg.sender */
returns (uint, uint, uint, uint, uint, uint, uint, uint, uint, uint)
{
return (phaseStartBlocknums[0],
phaseStartBlocknums[1],
phaseStartBlocknums[2],
phaseStartBlocknums[3],
phaseStartBlocknums[4],
phaseStartTimestamps[0],
phaseStartTimestamps[1],
phaseStartTimestamps[2],
phaseStartTimestamps[3],
phaseStartTimestamps[4]
);
}
}
| Release the remaining balance to the beneficiary. | require(daiContract.transfer(beneficiary, getBalance()), "Final release transfer to beneficiary failed!");
| 6,363,387 | [
1,
7391,
326,
4463,
11013,
358,
326,
27641,
74,
14463,
814,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
2414,
77,
8924,
18,
13866,
12,
70,
4009,
74,
14463,
814,
16,
2882,
6112,
1435,
3631,
315,
7951,
3992,
7412,
358,
27641,
74,
14463,
814,
2535,
4442,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// Prepared for BUchain Workshop by Murat Ögat
pragma solidity ^0.8.0;
import "./IBroker.sol";
import "../Utils/Ownable.sol";
import "../ERC20/IERC20.sol";
import "../Utils/IUniswapV3.sol";
contract Broker is IBroker, Ownable {
IERC20 private immutable currency;
IERC20 private immutable shares;
uint256 private price;
IQuoter private immutable uniswapQuoter = IQuoter(0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6);
ISwapRouter private immutable uniswapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564);
uint24 private constant UNISWAP_POOL_FEE_TIER = 3000;
event SharesBought(IERC20 indexed token, address who, uint256 amount, uint256 totPrice);
event SharesSold(IERC20 indexed token, address who, uint256 amount, uint256 totPrice);
constructor(IERC20 _shares, uint256 _price, IERC20 _currency, address _owner) Ownable(_owner) {
shares = _shares;
price = _price;
currency = _currency;
}
function getShares() external view returns (IERC20) {
return shares;
}
function getBaseCurrency() external view returns (IERC20) {
return currency;
}
function getPriceInBaseCurrency() external view returns (uint256) {
return price;
}
function setPriceInBaseCurrency(uint256 _price) external onlyOwner {
price = _price;
}
function getPrice(uint256 _amountShares) public view returns (uint256) {
return price * _amountShares;
}
function getPriceInETH(uint256 _amountShares) public returns (uint256) {
uint256 amountInBase = getPrice(_amountShares);
return uniswapQuoter.quoteExactOutputSingle(uniswapQuoter.WETH9(), address(currency), UNISWAP_POOL_FEE_TIER, amountInBase, 0);
}
function getPriceInToken(uint256 _amountShares, bytes memory path) external returns (uint256) {
uint256 amountInBase = getPrice(_amountShares);
return uniswapQuoter.quoteExactOutput(path, amountInBase);
}
function buyWithBaseCurrency(uint256 _amountShares) external {
uint256 totalPrice = getPrice(_amountShares);
currency.transferFrom(msg.sender, address(this), totalPrice);
shares.transfer(msg.sender, _amountShares);
emit SharesBought(shares, address(msg.sender), _amountShares, totalPrice);
}
function buyWithETH(uint256 _amountShares) external payable {
uint256 totalPriceBase = getPrice(_amountShares);
ISwapRouter.ExactOutputSingleParams memory params = ISwapRouter.ExactOutputSingleParams(
uniswapQuoter.WETH9(),
address(currency),
UNISWAP_POOL_FEE_TIER,
address(this),
block.timestamp,
totalPriceBase,
msg.value,
0
);
// Executes the swap returning the amountIn needed to spend to receive the desired amountOut.
uint256 amountIn = uniswapRouter.exactOutputSingle{value: msg.value}(params);
// For exact output swaps, the amountInMaximum may not have all been spent.
// If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender
if (amountIn < msg.value) {
uniswapRouter.refundETH();
payable(msg.sender).transfer(msg.value - amountIn);
}
shares.transfer(msg.sender, _amountShares);
emit SharesBought(shares, address(msg.sender), _amountShares, totalPriceBase);
}
function buyWithToken(uint256 _amountShares, address _tokenAddress, uint256 _amountInMaximum) external {
uint256 totalPriceBase = getPrice(_amountShares);
IERC20(_tokenAddress).transferFrom(msg.sender, address(this), _amountInMaximum);
IERC20(_tokenAddress).approve(address(uniswapRouter), _amountInMaximum);
ISwapRouter.ExactOutputParams memory params = ISwapRouter.ExactOutputParams({
path: abi.encodePacked(currency, UNISWAP_POOL_FEE_TIER, uniswapQuoter.WETH9(), UNISWAP_POOL_FEE_TIER, _tokenAddress),
recipient: msg.sender,
deadline: block.timestamp,
amountOut: totalPriceBase,
amountInMaximum: _amountInMaximum
});
// Executes the swap returning the amountIn needed to spend to receive the desired amountOut.
uint256 amountIn = uniswapRouter.exactOutput(params);
// For exact output swaps, the amountInMaximum may not have all been spent.
// If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender
if (amountIn < _amountInMaximum) {
IERC20(_tokenAddress).transfer(msg.sender, _amountInMaximum - amountIn);
}
shares.transfer(msg.sender, _amountShares);
emit SharesBought(shares, address(msg.sender), _amountShares, totalPriceBase);
}
function buyWithTokenPath(uint256 _amountShares, address _tokenAddress, bytes calldata path, uint256 _amountInMaximum) external {
uint256 totalPriceBase = getPrice(_amountShares);
uint256 balanceBefore = IERC20(currency).balanceOf(address(this));
IERC20(_tokenAddress).transferFrom(msg.sender, address(this), _amountInMaximum);
IERC20(_tokenAddress).approve(address(uniswapRouter), _amountInMaximum);
ISwapRouter.ExactOutputParams memory params = ISwapRouter.ExactOutputParams({
path: path,
recipient: msg.sender,
deadline: block.timestamp,
amountOut: totalPriceBase,
amountInMaximum: _amountInMaximum
});
// Executes the swap returning the amountIn needed to spend to receive the desired amountOut.
uint256 amountIn = uniswapRouter.exactOutput(params);
uint256 balanceAfter = IERC20(currency).balanceOf(address(this));
require(totalPriceBase == (balanceAfter - balanceBefore), "Failed to receive base");
// For exact output swaps, the amountInMaximum may not have all been spent.
// If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender
if (amountIn < _amountInMaximum) {
IERC20(_tokenAddress).transfer(msg.sender, _amountInMaximum - amountIn);
}
shares.transfer(msg.sender, _amountShares);
emit SharesBought(shares, address(msg.sender), _amountShares, totalPriceBase);
}
function sellForBaseCurrency(uint256 _amountShares) external {
uint256 totalPrice = getPrice(_amountShares);
shares.transferFrom(msg.sender, address(this), _amountShares);
currency.transfer(msg.sender, totalPrice);
emit SharesSold(shares, address(msg.sender), _amountShares, totalPrice);
}
function sellForWETH(uint256 _amountShares) external {
shares.transferFrom(msg.sender, address(this), _amountShares);
uint256 totalPriceBase = getPrice(_amountShares);
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams(
address(currency),
uniswapQuoter.WETH9(),
UNISWAP_POOL_FEE_TIER,
msg.sender,
block.timestamp,
totalPriceBase,
0,
0
);
currency.approve(address(uniswapRouter), totalPriceBase);
uniswapRouter.exactInputSingle(params);
emit SharesSold(shares, address(msg.sender), _amountShares, totalPriceBase);
}
function withdrawShares(address _recipient, uint256 _amount) external onlyOwner {
withdrawToken(address(shares), _recipient, _amount);
}
function withdrawCurrency(address _recipient, uint256 _amount) external onlyOwner {
withdrawToken(address(currency), _recipient, _amount);
}
function withdrawToken(address _token, address _recipient, uint256 _amount) public onlyOwner {
IERC20(_token).transfer(_recipient, _amount);
}
function withdrawETH(address _recipient, uint256 _amount) external onlyOwner {
payable(_recipient).transfer(_amount);
}
receive() external payable {}
} | For exact output swaps, the amountInMaximum may not have all been spent. If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender | function buyWithTokenPath(uint256 _amountShares, address _tokenAddress, bytes calldata path, uint256 _amountInMaximum) external {
uint256 totalPriceBase = getPrice(_amountShares);
uint256 balanceBefore = IERC20(currency).balanceOf(address(this));
IERC20(_tokenAddress).transferFrom(msg.sender, address(this), _amountInMaximum);
IERC20(_tokenAddress).approve(address(uniswapRouter), _amountInMaximum);
ISwapRouter.ExactOutputParams memory params = ISwapRouter.ExactOutputParams({
path: path,
recipient: msg.sender,
deadline: block.timestamp,
amountOut: totalPriceBase,
amountInMaximum: _amountInMaximum
});
uint256 balanceAfter = IERC20(currency).balanceOf(address(this));
require(totalPriceBase == (balanceAfter - balanceBefore), "Failed to receive base");
if (amountIn < _amountInMaximum) {
IERC20(_tokenAddress).transfer(msg.sender, _amountInMaximum - amountIn);
}
shares.transfer(msg.sender, _amountShares);
emit SharesBought(shares, address(msg.sender), _amountShares, totalPriceBase);
}
| 6,385,146 | [
1,
1290,
5565,
876,
1352,
6679,
16,
326,
3844,
382,
13528,
2026,
486,
1240,
777,
2118,
26515,
18,
971,
326,
3214,
3844,
26515,
261,
8949,
382,
13,
353,
5242,
2353,
326,
1269,
4207,
3844,
16,
732,
1297,
16255,
326,
1234,
18,
15330,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
30143,
1190,
1345,
743,
12,
11890,
5034,
389,
8949,
24051,
16,
1758,
389,
2316,
1887,
16,
1731,
745,
892,
589,
16,
2254,
5034,
389,
8949,
382,
13528,
13,
3903,
288,
203,
3639,
2254,
5034,
2078,
5147,
2171,
273,
25930,
24899,
8949,
24051,
1769,
203,
3639,
2254,
5034,
11013,
4649,
273,
467,
654,
39,
3462,
12,
7095,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
467,
654,
39,
3462,
24899,
2316,
1887,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
382,
13528,
1769,
203,
3639,
467,
654,
39,
3462,
24899,
2316,
1887,
2934,
12908,
537,
12,
2867,
12,
318,
291,
91,
438,
8259,
3631,
389,
8949,
382,
13528,
1769,
203,
203,
3639,
4437,
91,
438,
8259,
18,
14332,
1447,
1370,
3778,
859,
273,
4437,
91,
438,
8259,
18,
14332,
1447,
1370,
12590,
203,
5411,
589,
30,
589,
16,
203,
5411,
8027,
30,
1234,
18,
15330,
16,
203,
5411,
14096,
30,
1203,
18,
5508,
16,
203,
5411,
3844,
1182,
30,
2078,
5147,
2171,
16,
203,
5411,
3844,
382,
13528,
30,
389,
8949,
382,
13528,
203,
3639,
15549,
203,
203,
3639,
2254,
5034,
11013,
4436,
273,
467,
654,
39,
3462,
12,
7095,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
2583,
12,
4963,
5147,
2171,
422,
261,
12296,
4436,
300,
11013,
4649,
3631,
315,
2925,
358,
6798,
1026,
8863,
203,
203,
3639,
309,
261,
8949,
382,
411,
389,
8949,
382,
13528,
13,
288,
203,
5411,
467,
654,
39,
3462,
24899,
2316,
1887,
2934,
13866,
2
] |
./full_match/4/0x4e87720bE34A1a2c810b939dbC66E3FCe3e02513/sources/contracts/MeetBOB.sol | * @notice global purchase function used in early access and public sale @param amount the amount of BOBs to purchase/ | function _purchase(uint256 amount) private {
uint256 supply = totalSupply();
require(supply + amount <= maxSupply, "Exceeds maximum supply of BOB");
for (uint256 i; i < amount; i++) {
_safeMint(msg.sender, supply + i);
}
}
| 12,299,820 | [
1,
6347,
23701,
445,
1399,
316,
11646,
2006,
471,
1071,
272,
5349,
225,
3844,
326,
3844,
434,
605,
5704,
87,
358,
23701,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
12688,
12104,
12,
11890,
5034,
3844,
13,
3238,
288,
203,
3639,
2254,
5034,
14467,
273,
2078,
3088,
1283,
5621,
203,
3639,
2583,
12,
2859,
1283,
397,
3844,
1648,
943,
3088,
1283,
16,
315,
424,
5288,
87,
4207,
14467,
434,
605,
5704,
8863,
203,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
3844,
31,
277,
27245,
288,
203,
5411,
389,
4626,
49,
474,
12,
3576,
18,
15330,
16,
14467,
397,
277,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x25245941137d9C85B5D48aE8d7788aA841BEB9aE/sources/contracts/staking/MasterBids.sol | @notice Add a new lp to the pool. Can only be called by the owner. @dev Reverts if the same LP token is added more than once. @param _lpToken the corresponding lp token @param _rewarder the contract that implements "onReward(user)" that is called on user operation update PoolInfoV3 with the new LP | function add(IERC20 _lpToken, IRewarder _rewarder) external onlyOwner {
require(Address.isContract(address(_lpToken)), "add: LP token must be a valid contract");
require(!lpTokens.contains(address(_lpToken)), "add: LP already added");
poolInfoV3.push(
PoolInfoV3({
lpToken: _lpToken,
rewarder: _rewarder,
lastRewardTimestamp: uint40(block.timestamp),
accBidsPerShare: 0,
accBidsPerFactorShare: 0,
sumOfFactors: 0,
periodFinish: uint40(block.timestamp),
rewardRate: 0
})
);
assetPid[address(_lpToken)] = poolInfoV3.length;
emit Add(poolInfoV3.length - 1, _lpToken);
}
| 3,100,017 | [
1,
986,
279,
394,
12423,
358,
326,
2845,
18,
4480,
1338,
506,
2566,
635,
326,
3410,
18,
225,
868,
31537,
309,
326,
1967,
511,
52,
1147,
353,
3096,
1898,
2353,
3647,
18,
225,
389,
9953,
1345,
326,
4656,
12423,
1147,
225,
389,
266,
20099,
326,
6835,
716,
4792,
315,
265,
17631,
1060,
12,
1355,
2225,
716,
353,
2566,
603,
729,
1674,
1089,
8828,
966,
58,
23,
598,
326,
394,
511,
52,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
12,
45,
654,
39,
3462,
389,
9953,
1345,
16,
15908,
359,
297,
765,
389,
266,
20099,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
1887,
18,
291,
8924,
12,
2867,
24899,
9953,
1345,
13,
3631,
315,
1289,
30,
511,
52,
1147,
1297,
506,
279,
923,
6835,
8863,
203,
3639,
2583,
12,
5,
9953,
5157,
18,
12298,
12,
2867,
24899,
9953,
1345,
13,
3631,
315,
1289,
30,
511,
52,
1818,
3096,
8863,
203,
203,
3639,
2845,
966,
58,
23,
18,
6206,
12,
203,
5411,
8828,
966,
58,
23,
12590,
203,
7734,
12423,
1345,
30,
389,
9953,
1345,
16,
203,
7734,
283,
20099,
30,
389,
266,
20099,
16,
203,
7734,
1142,
17631,
1060,
4921,
30,
2254,
7132,
12,
2629,
18,
5508,
3631,
203,
7734,
4078,
38,
2232,
2173,
9535,
30,
374,
16,
203,
7734,
4078,
38,
2232,
2173,
6837,
9535,
30,
374,
16,
203,
7734,
2142,
951,
23535,
30,
374,
16,
203,
7734,
3879,
11641,
30,
2254,
7132,
12,
2629,
18,
5508,
3631,
203,
7734,
19890,
4727,
30,
374,
203,
5411,
289,
13,
203,
3639,
11272,
203,
3639,
3310,
12478,
63,
2867,
24899,
9953,
1345,
25887,
273,
2845,
966,
58,
23,
18,
2469,
31,
203,
203,
3639,
3626,
1436,
12,
6011,
966,
58,
23,
18,
2469,
300,
404,
16,
389,
9953,
1345,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x4C3071eFd04b836C9E13D8811107Ec1F4A24f0D8/sources/PhilippCoin.sol | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract PhilippCoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() {
symbol = "PHILIPP";
name = "PhilippCoin";
decimals = 0;
_totalSupply = 1337000420;
balances[0xe66bA65d2e7c61df343D3Df7A28F94fcd8c06240] = _totalSupply;
emit Transfer(address(0), 0xe66bA65d2e7c61df343D3Df7A28F94fcd8c06240, _totalSupply);
}
function totalSupply() public override view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public override view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public override returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public override returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public override view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 9,527,926 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4360,
330,
15491,
27055,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
3885,
1435,
288,
203,
3639,
3273,
273,
315,
8939,
45,
2053,
6584,
14432,
203,
3639,
508,
273,
315,
3731,
330,
15491,
27055,
14432,
203,
3639,
15105,
273,
374,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
30537,
26874,
3028,
3462,
31,
203,
3639,
324,
26488,
63,
20,
6554,
6028,
70,
37,
9222,
72,
22,
73,
27,
71,
9498,
2180,
5026,
23,
40,
23,
40,
74,
27,
37,
6030,
42,
11290,
74,
4315,
28,
71,
7677,
28784,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
374,
6554,
6028,
70,
37,
9222,
72,
22,
73,
27,
71,
9498,
2180,
5026,
23,
40,
23,
40,
74,
27,
37,
6030,
42,
11290,
74,
4315,
28,
71,
7677,
28784,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
3849,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
1147,
5541,
2
] |
./full_match/83/0x48ef19252C6c59c5CF1e5Bd87DAeE0A2c5BA7cEE/sources/contracts/CToken/CToken.sol | Calculate new borrow balance using the interest index: recentBorrowBalance = borrower.borrowBalance market.borrowIndex / borrower.borrowIndex/ | (mathErr, principalTimesIndex) = borrowSnapshot.principal.mulUInt(borrowIndex);
| 9,556,587 | [
1,
8695,
394,
29759,
11013,
1450,
326,
16513,
770,
30,
225,
8399,
38,
15318,
13937,
273,
29759,
264,
18,
70,
15318,
13937,
225,
13667,
18,
70,
15318,
1016,
342,
29759,
264,
18,
70,
15318,
1016,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
261,
15949,
2524,
16,
8897,
10694,
1016,
13,
273,
29759,
4568,
18,
26138,
18,
16411,
14342,
12,
70,
15318,
1016,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "../../openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./BridgeToken.sol";
/**
* @title GoAssetBank
* @dev Manages the deployment and minting of ERC20 compatible BridgeTokens
* which represent assets issued by Go contracts.
* @dev 为chain33上的go合约发行的资产进行BridgeTokens合约部署,铸币和销毁
**/
contract GoAssetBank {
using SafeMath for uint256;
uint256 public bridgeTokenCount;
mapping(address => bool) public bridgeTokenWhitelist;
mapping(bytes32 => bool) public bridgeTokenCreated;
mapping(bytes32 => GoAssetDeposit) goAssetDeposits;
mapping(bytes32 => GoAssetBurn) goAssetBurns;
mapping(address => DepositBurnCount) depositBurnCounts;
mapping(bytes32 => address) public token2address;
struct GoAssetDeposit {
address goAssetSender;
address payable chain33Recipient;
address bridgeTokenAddress;
uint256 amount;
bool exist;
uint256 nonce;
}
struct DepositBurnCount {
uint256 depositCount;
uint256 burnCount;
}
struct GoAssetBurn {
address goAssetSender;
address payable chain33Owner;
address bridgeTokenAddress;
uint256 amount;
uint256 nonce;
}
/*
* @dev: Event declarations
*/
event LogNewBridgeToken(
address _token,
string _symbol
);
event LogBridgeTokenMint(
address _token,
string _symbol,
uint256 _amount,
address _beneficiary
);
event LogGoAssetTokenBurn(
address _token,
string _symbol,
uint256 _amount,
address _ownerFrom,
address _goAssetReceiver,
uint256 _nonce
);
/*
* @dev: Modifier to make sure this symbol not created now
*/
modifier notCreated(string memory _symbol)
{
require(
!hasBridgeTokenCreated(_symbol),
"The symbol has been created already"
);
_;
}
/*
* @dev: Modifier to make sure this symbol not created now
*/
modifier created(string memory _symbol)
{
require(
hasBridgeTokenCreated(_symbol),
"The symbol has not been created yet"
);
_;
}
/*
* @dev: Constructor, sets bridgeTokenCount
*/
constructor () public {
bridgeTokenCount = 0;
}
/*
* @dev: check whether this symbol has been created yet or not
*
* @param _symbol: token symbol
* @return: true or false
*/
function hasBridgeTokenCreated(string memory _symbol) public view returns(bool) {
bytes32 symHash = keccak256(abi.encodePacked(_symbol));
return bridgeTokenCreated[symHash];
}
/*
* @dev: Creates a new GoAssetDeposit with a unique ID
*
* @param _goAssetSender: The _goAssetSender sender's address.
* @param _chain33Recipient: The intended recipient's Chain33 address.
* @param _token: The currency type
* @param _amount: The amount in the deposit.
* @return: The newly created GoAssetSenderDeposit's unique id.
*/
function newGoAssetDeposit(
address _goAssetSender,
address payable _chain33Recipient,
address _token,
uint256 _amount
)
internal
returns(bytes32)
{
DepositBurnCount memory depositBurnCount = depositBurnCounts[_token];
depositBurnCount.depositCount = depositBurnCount.depositCount.add(1);
depositBurnCounts[_token] = depositBurnCount;
bytes32 depositID = keccak256(
abi.encodePacked(
_goAssetSender,
_chain33Recipient,
_token,
_amount,
depositBurnCount.depositCount
)
);
goAssetDeposits[depositID] = GoAssetDeposit(
_goAssetSender,
_chain33Recipient,
_token,
_amount,
true,
depositBurnCount.depositCount
);
return depositID;
}
/*
* @dev: Creates a new GoAssetBurn with a unique ID
*
* @param _goAssetSender: The go Asset Sender address
* @param _chain33Owner: The owner's Chain33 address.
* @param _token: The token Address
* @param _amount: The amount to be burned.
* @param _nonce: The nonce indicates the burn count for this token
* @return: The newly created GoAssetBurn's unique id.
*/
function newGoAssetBurn(
address _goAssetSender,
address payable _chain33Owner,
address _token,
uint256 _amount,
uint256 nonce
)
internal
returns(bytes32)
{
bytes32 burnID = keccak256(
abi.encodePacked(
_goAssetSender,
_chain33Owner,
_token,
_amount,
nonce
)
);
goAssetBurns[burnID] = GoAssetBurn(
_goAssetSender,
_chain33Owner,
_token,
_amount,
nonce
);
return burnID;
}
/*
* @dev: Deploys a new BridgeToken contract
*
* @param _symbol: The BridgeToken's symbol
*/
function deployNewBridgeToken(
string memory _symbol
)
internal
notCreated(_symbol)
returns(address)
{
bridgeTokenCount = bridgeTokenCount.add(1);
// Deploy new bridge token contract
BridgeToken newBridgeToken = (new BridgeToken)(_symbol);
// Set address in tokens mapping
address newBridgeTokenAddress = address(newBridgeToken);
bridgeTokenWhitelist[newBridgeTokenAddress] = true;
bytes32 symHash = keccak256(abi.encodePacked(_symbol));
bridgeTokenCreated[symHash] = true;
depositBurnCounts[newBridgeTokenAddress] = DepositBurnCount(
uint256(0),
uint256(0));
token2address[symHash] = newBridgeTokenAddress;
emit LogNewBridgeToken(
newBridgeTokenAddress,
_symbol
);
return newBridgeTokenAddress;
}
/*
* @dev: Mints new goAsset tokens
*
* @param _goAssetSender: The _goAssetSender sender's address.
* @param _chain33Recipient: The intended recipient's Chain33 address.
* @param _goAssetTokenAddress: The currency type
* @param _symbol: goAsset token symbol
* @param _amount: number of goAsset tokens to be minted
*/
function mintNewBridgeTokens(
address _goAssetSender,
address payable _intendedRecipient,
address _bridgeTokenAddress,
string memory _symbol,
uint256 _amount
)
internal
{
// Must be whitelisted bridge token
require(
bridgeTokenWhitelist[_bridgeTokenAddress],
"Token must be a whitelisted bridge token"
);
// Mint bridge tokens
require(
BridgeToken(_bridgeTokenAddress).mint(
_intendedRecipient,
_amount
),
"Attempted mint of bridge tokens failed"
);
newGoAssetDeposit(
_goAssetSender,
_intendedRecipient,
_bridgeTokenAddress,
_amount
);
emit LogBridgeTokenMint(
_bridgeTokenAddress,
_symbol,
_amount,
_intendedRecipient
);
}
/*
* @dev: Burn goAsset tokens
*
* @param _from: The address to be burned from
* @param _goAssetReceiver: The receiver's GoAsset address in bytes.
* @param _goAssetTokenAddress: The token address of goAsset asset issued on chain33
* @param _amount: number of goAsset tokens to be minted
*/
function burnGoAssetTokens(
address payable _from,
address _goAssetReceiver,
address _goAssetTokenAddress,
uint256 _amount
)
internal
{
// Must be whitelisted bridge token
require(
bridgeTokenWhitelist[_goAssetTokenAddress],
"Token must be a whitelisted bridge token"
);
// burn bridge tokens
BridgeToken bridgeTokenInstance = BridgeToken(_goAssetTokenAddress);
bridgeTokenInstance.burnFrom(_from, _amount);
DepositBurnCount memory depositBurnCount = depositBurnCounts[_goAssetTokenAddress];
require(
depositBurnCount.burnCount + 1 > depositBurnCount.burnCount,
"burn nonce is not available"
);
depositBurnCount.burnCount = depositBurnCount.burnCount.add(1);
depositBurnCounts[_goAssetTokenAddress] = depositBurnCount;
newGoAssetBurn(
_goAssetReceiver,
_from,
_goAssetTokenAddress,
_amount,
depositBurnCount.burnCount
);
emit LogGoAssetTokenBurn(
_goAssetTokenAddress,
bridgeTokenInstance.symbol(),
_amount,
_from,
_goAssetReceiver,
depositBurnCount.burnCount
);
}
/*
* @dev: Checks if an individual GoAssetDeposit exists.
*
* @param _id: The unique GoAssetDeposit's id.
* @return: Boolean indicating if the GoAssetDeposit exists in memory.
*/
function isLockedGoAssetDeposit(
bytes32 _id
)
internal
view
returns(bool)
{
return(goAssetDeposits[_id].exist);
}
/*
* @dev: Gets an item's information
*
* @param _Id: The item containing the desired information.
* @return: Sender's address.
* @return: Recipient's address in bytes.
* @return: Token address.
* @return: Amount of chain33/erc20 in the item.
* @return: Unique nonce of the item.
*/
function getGoAssetDeposit(
bytes32 _id
)
internal
view
returns(address, address payable, address, uint256)
{
GoAssetDeposit memory deposit = goAssetDeposits[_id];
return(
deposit.goAssetSender,
deposit.chain33Recipient,
deposit.bridgeTokenAddress,
deposit.amount
);
}
function getToken2address(string memory _symbol)
created(_symbol)
public view returns(address)
{
bytes32 symHash = keccak256(abi.encodePacked(_symbol));
return token2address[symHash];
}
} | @dev: Mints new goAsset tokens @param _goAssetSender: The _goAssetSender sender's address. @param _chain33Recipient: The intended recipient's Chain33 address. @param _goAssetTokenAddress: The currency type @param _symbol: goAsset token symbol @param _amount: number of goAsset tokens to be minted/ Must be whitelisted bridge token Mint bridge tokens | function mintNewBridgeTokens(
address _goAssetSender,
address payable _intendedRecipient,
address _bridgeTokenAddress,
string memory _symbol,
uint256 _amount
)
internal
{
require(
bridgeTokenWhitelist[_bridgeTokenAddress],
"Token must be a whitelisted bridge token"
);
require(
BridgeToken(_bridgeTokenAddress).mint(
_intendedRecipient,
_amount
),
"Attempted mint of bridge tokens failed"
);
newGoAssetDeposit(
_goAssetSender,
_intendedRecipient,
_bridgeTokenAddress,
_amount
);
emit LogBridgeTokenMint(
_bridgeTokenAddress,
_symbol,
_amount,
_intendedRecipient
);
}
| 13,044,004 | [
1,
30,
490,
28142,
394,
1960,
6672,
2430,
225,
389,
3240,
6672,
12021,
30,
225,
1021,
389,
3240,
6672,
12021,
5793,
1807,
1758,
18,
225,
389,
5639,
3707,
18241,
30,
1021,
12613,
8027,
1807,
7824,
3707,
1758,
18,
225,
389,
3240,
6672,
1345,
1887,
30,
1021,
5462,
618,
225,
389,
7175,
30,
1960,
6672,
1147,
3273,
225,
389,
8949,
30,
1300,
434,
1960,
6672,
2430,
358,
506,
312,
474,
329,
19,
6753,
506,
26944,
10105,
1147,
490,
474,
10105,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
377,
445,
312,
474,
1908,
13691,
5157,
12,
203,
3639,
1758,
225,
389,
3240,
6672,
12021,
16,
203,
3639,
1758,
8843,
429,
389,
474,
3934,
18241,
16,
203,
3639,
1758,
389,
18337,
1345,
1887,
16,
203,
3639,
533,
3778,
389,
7175,
16,
203,
3639,
2254,
5034,
389,
8949,
203,
565,
262,
203,
3639,
2713,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
10105,
1345,
18927,
63,
67,
18337,
1345,
1887,
6487,
203,
5411,
315,
1345,
1297,
506,
279,
26944,
10105,
1147,
6,
203,
3639,
11272,
203,
203,
3639,
2583,
12,
203,
5411,
24219,
1345,
24899,
18337,
1345,
1887,
2934,
81,
474,
12,
203,
7734,
389,
474,
3934,
18241,
16,
203,
7734,
389,
8949,
203,
5411,
262,
16,
203,
5411,
315,
28788,
312,
474,
434,
10105,
2430,
2535,
6,
203,
3639,
11272,
203,
203,
3639,
394,
5741,
6672,
758,
1724,
12,
203,
5411,
389,
3240,
6672,
12021,
16,
203,
5411,
389,
474,
3934,
18241,
16,
203,
5411,
389,
18337,
1345,
1887,
16,
203,
5411,
389,
8949,
203,
3639,
11272,
203,
203,
3639,
3626,
1827,
13691,
1345,
49,
474,
12,
203,
5411,
389,
18337,
1345,
1887,
16,
203,
5411,
389,
7175,
16,
203,
5411,
389,
8949,
16,
203,
5411,
389,
474,
3934,
18241,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.7.0 < 0.8.0;
contract AddressBook {
//maps an address to an address array
mapping(address => address[]) private _addresses;
//maps an address to the aliases of the related addresses
// when you are mapping a key to another mapping, the key gets mapped to the value of the second mapping
mapping(address => mapping(address => string)) private _aliases;
// array types (reference types) require the memory keyword
function getAddressArray(address adr) public view returns(address[] memory) {
return _addresses[adr];
}
//function to add addresses to your AddressBook
function addAddress(address adr, string alias) public {
_addresses[msg.sender].push(adr);
_addresses[msg.sender][adr] = alias; //This is how you assign values to mapping of a mapping wale case mein
}
function removeAddress(address adr) public {
uint length = _addresses[msg.sender].length;
for(uint i = 0; i < length; i++) {
if(adr == _addresses[msg.sender][i]) {
// The 1 < condition is making sure that the address book of msg.sender had more than 1 contact, else there is no point of deleting and shifitng stuff
if(1 < _addresses[msg.sender].length && i < length - 1) {
// Migrate the last address from the address book to the index from where the address was removed
_addresses[msg.sender][i] = _addresses[msg.sender][length-1];
}
delete _addresses[msg.sender][length-1];
_addresses[msg.sender].length--;
delete aliases[msg.sender][adr];
break;
}
}
}
function getAlias(address addrOwner, address addr) public view returns(string memory) {
return _aliases[addrOwner][addr];
}
}
| maps an address to an address arraymaps an address to the aliases of the related addresses when you are mapping a key to another mapping, the key gets mapped to the value of the second mapping array types (reference types) require the memory keyword | contract AddressBook {
mapping(address => address[]) private _addresses;
mapping(address => mapping(address => string)) private _aliases;
function getAddressArray(address adr) public view returns(address[] memory) {
return _addresses[adr];
}
function addAddress(address adr, string alias) public {
_addresses[msg.sender].push(adr);
}
function removeAddress(address adr) public {
uint length = _addresses[msg.sender].length;
for(uint i = 0; i < length; i++) {
if(adr == _addresses[msg.sender][i]) {
if(1 < _addresses[msg.sender].length && i < length - 1) {
_addresses[msg.sender][i] = _addresses[msg.sender][length-1];
}
delete _addresses[msg.sender][length-1];
_addresses[msg.sender].length--;
delete aliases[msg.sender][adr];
break;
}
}
}
function removeAddress(address adr) public {
uint length = _addresses[msg.sender].length;
for(uint i = 0; i < length; i++) {
if(adr == _addresses[msg.sender][i]) {
if(1 < _addresses[msg.sender].length && i < length - 1) {
_addresses[msg.sender][i] = _addresses[msg.sender][length-1];
}
delete _addresses[msg.sender][length-1];
_addresses[msg.sender].length--;
delete aliases[msg.sender][adr];
break;
}
}
}
function removeAddress(address adr) public {
uint length = _addresses[msg.sender].length;
for(uint i = 0; i < length; i++) {
if(adr == _addresses[msg.sender][i]) {
if(1 < _addresses[msg.sender].length && i < length - 1) {
_addresses[msg.sender][i] = _addresses[msg.sender][length-1];
}
delete _addresses[msg.sender][length-1];
_addresses[msg.sender].length--;
delete aliases[msg.sender][adr];
break;
}
}
}
function removeAddress(address adr) public {
uint length = _addresses[msg.sender].length;
for(uint i = 0; i < length; i++) {
if(adr == _addresses[msg.sender][i]) {
if(1 < _addresses[msg.sender].length && i < length - 1) {
_addresses[msg.sender][i] = _addresses[msg.sender][length-1];
}
delete _addresses[msg.sender][length-1];
_addresses[msg.sender].length--;
delete aliases[msg.sender][adr];
break;
}
}
}
function getAlias(address addrOwner, address addr) public view returns(string memory) {
return _aliases[addrOwner][addr];
}
}
| 2,540,434 | [
1,
10711,
392,
1758,
358,
392,
1758,
526,
10711,
392,
1758,
358,
326,
6900,
434,
326,
3746,
6138,
1347,
1846,
854,
2874,
279,
498,
358,
4042,
2874,
16,
326,
498,
5571,
5525,
358,
326,
460,
434,
326,
2205,
2874,
526,
1953,
261,
6180,
1953,
13,
2583,
326,
3778,
4932,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
5267,
9084,
288,
203,
565,
2874,
12,
2867,
516,
1758,
63,
5717,
3238,
389,
13277,
31,
203,
377,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
533,
3719,
3238,
389,
13831,
31,
203,
377,
203,
203,
565,
445,
14808,
1076,
12,
2867,
1261,
86,
13,
1071,
1476,
1135,
12,
2867,
8526,
3778,
13,
288,
203,
3639,
327,
389,
13277,
63,
361,
86,
15533,
203,
565,
289,
203,
377,
203,
565,
445,
527,
1887,
12,
2867,
1261,
86,
16,
533,
2308,
13,
1071,
288,
203,
3639,
389,
13277,
63,
3576,
18,
15330,
8009,
6206,
12,
361,
86,
1769,
203,
565,
289,
203,
377,
203,
565,
445,
1206,
1887,
12,
2867,
1261,
86,
13,
1071,
288,
203,
3639,
2254,
769,
273,
389,
13277,
63,
3576,
18,
15330,
8009,
2469,
31,
203,
3639,
364,
12,
11890,
277,
273,
374,
31,
277,
411,
769,
31,
277,
27245,
288,
203,
5411,
309,
12,
361,
86,
422,
389,
13277,
63,
3576,
18,
15330,
6362,
77,
5717,
288,
203,
7734,
309,
12,
21,
411,
389,
13277,
63,
3576,
18,
15330,
8009,
2469,
597,
277,
411,
769,
300,
404,
13,
288,
203,
10792,
389,
13277,
63,
3576,
18,
15330,
6362,
77,
65,
273,
389,
13277,
63,
3576,
18,
15330,
6362,
2469,
17,
21,
15533,
203,
7734,
289,
203,
7734,
1430,
389,
13277,
63,
3576,
18,
15330,
6362,
2469,
17,
21,
15533,
203,
7734,
389,
13277,
63,
3576,
18,
15330,
8009,
2469,
413,
31,
203,
7734,
1430,
6900,
63,
3576,
18,
15330,
6362,
361,
86,
15533,
203,
7734,
898,
31,
2
] |
// SPDX-License-Identifier: UNLISCENSED
pragma solidity 0.6.0;
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// interface BEP20 {
// /**
// * @dev Returns the amount of tokens in existence.
// */
// function totalSupply() external view returns (uint256);
// /**
// * @dev Returns the amount of tokens owned by `account`.
// */
// function balanceOf(address account) external view returns (uint256);
// /**
// * @dev Moves `amount` tokens from the caller's account to `recipient`.
// *
// * Returns a boolean value indicating whether the operation succeeded.
// *
// * Emits a {Transfer} event.
// */
// function transfer(address recipient, uint256 amount) external returns (bool);
// /**
// * @dev Returns the remaining number of tokens that `spender` will be
// * allowed to spend on behalf of `owner` through {transferFrom}. This is
// * zero by default.
// *
// * This value changes when {approve} or {transferFrom} are called.
// */
// function allowance(address owner, address spender) external view returns (uint256);
// /**
// * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
// *
// * Returns a boolean value indicating whether the operation succeeded.
// *
// * IMPORTANT: Beware that changing an allowance with this method brings the risk
// * that someone may use both the old and the new allowance by unfortunate
// * transaction ordering. One possible solution to mitigate this race
// * condition is to first reduce the spender's allowance to 0 and set the
// * desired value afterwards:
// * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
// *
// * Emits an {Approval} event.
// */
// function approve(address spender, uint256 amount) external returns (bool);
// /**
// * @dev Moves `amount` tokens from `sender` to `recipient` using the
// * allowance mechanism. `amount` is then deducted from the caller's
// * allowance.
// *
// * Returns a boolean value indicating whether the operation succeeded.
// *
// * Emits a {Transfer} event.
// */
// function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
// /**
// * @dev Emitted when `value` tokens are moved from one account (`from`) to
// * another (`to`).
// *
// * Note that `value` may be zero.
// */
// event Transfer(address indexed from, address indexed to, uint256 value);
// /**
// * @dev Emitted when the allowance of a `spender` for an `owner` is set by
// * a call to {approve}. `value` is the new allowance.
// */
// event Approval(address indexed owner, address indexed spender, uint256 value);
// }
// contract CSMToken is Context, BEP20, Ownable {
// using SafeMath for uint256;
// mapping(address => uint256) private _balances;
// mapping(address => mapping(address => uint256)) private _allowances;
// uint256 private _totalSupply;
// uint8 private _decimals;
// string private _symbol;
// string private _name;
// uint256 public _decimalFactor;
// constructor() public payable {
// // _name = "CSM Token";
// // _symbol = "CSM";
// // _decimals = 5;
// // _decimalFactor = 10**5;
// // _totalSupply = 2000000 * _decimalFactor;
// }
// function getOwner() external view returns (address) {
// return owner();
// }
// function decimals() external view returns (uint8) {
// return _decimals;
// }
// function decimalFactor() external view returns (uint256) {
// return _decimalFactor;
// }
// function symbol() external view returns (string memory) {
// return _symbol;
// }
// function name() external view returns (string memory) {
// return _name;
// }
// // function totalSupply() external view returns (uint256) {
// // return _totalSupply;
// // }
// function balanceOf(address account) external view returns (uint256) {
// return _balances[account];
// }
// function transfer(address recipient, uint256 amount)
// external
// returns (bool)
// {
// _transfer(_msgSender(), recipient, amount);
// return true;
// }
// function allowance(address owner, address spender)
// external
// view
// returns (uint256)
// {
// return _allowances[owner][spender];
// }
// function approve(address spender, uint256 amount) external returns (bool) {
// _approve(_msgSender(), spender, amount);
// return true;
// }
// function transferFrom(
// address sender,
// address recipient,
// uint256 amount
// ) external 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
// returns (bool)
// {
// _approve(
// _msgSender(),
// spender,
// _allowances[_msgSender()][spender].add(addedValue)
// );
// return true;
// }
// function decreaseAllowance(address spender, uint256 subtractedValue)
// public
// returns (bool)
// {
// _approve(
// _msgSender(),
// spender,
// _allowances[_msgSender()][spender].sub(
// subtractedValue,
// "ERC20: decreased allowance below zero"
// )
// );
// return true;
// }
// function _transfer(
// address sender,
// address recipient,
// uint256 amount
// ) internal {
// require(
// sender != address(0),
// "ERC2020: transfer from the zero address"
// );
// require(
// recipient != address(0),
// "ERC2020: transfer to the zero address"
// );
// _balances[sender] = _balances[sender].sub(
// amount,
// "ERC20: transfer amount exceeds balance"
// );
// _balances[recipient] = _balances[recipient].add(amount);
// emit Transfer(sender, recipient, amount);
// }
// function _approve(
// address owner,
// address spender,
// uint256 amount
// ) internal {
// require(owner != address(0), "ERC20: approve from the zero address");
// require(spender != address(0), "ERC20: approve to the zero address");
// _allowances[owner][spender] = amount;
// emit Approval(owner, spender, amount);
// }
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BharatToken is IERC20 {
using SafeMath for uint256;
event Bought(uint256 amount);
event Sold(uint256 amount);
event TransferSent(address _from, address _destAddr, uint _amount);
// BEP20 public token;
string public constant name = "Bharat Token";
string public constant symbol = "Bharat";
uint8 public constant decimals = 5;
uint256 public _decimalFactor =10**5;
uint256 tokenBalance;
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Transfer(address indexed from, address indexed to, uint tokens);
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(address => mapping(address => uint256)) private _allowances;
// uint256 totalSupply_ = 1000000000000000000000000;
uint256 totalSupply_ = 1000000 * _decimalFactor;
constructor() public {
balances[msg.sender] = totalSupply_;
}
function totalSupply() public override view returns (uint256) {
return totalSupply_;
}
function balanceOf(address tokenOwner) public override view returns (uint256) {
return balances[tokenOwner];
}
function decimalFactor() external view returns (uint256) {
return _decimalFactor;
}
function transfer(address receiver, uint256 numTokens) public override returns (bool) {
require(numTokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(numTokens);
balances[receiver] = balances[receiver].add(numTokens);
emit Transfer(msg.sender, receiver, numTokens);
return true;
}
function approve(address delegate, uint256 numTokens) public override returns (bool) {
allowed[msg.sender][delegate] = numTokens;
emit Approval(msg.sender, delegate, numTokens);
return true;
}
function allowance(address owner, address delegate) public override view returns (uint) {
return allowed[owner][delegate];
}
function transferFrom(address owner, address buyer, uint256 numTokens) public override returns (bool) {
require(numTokens <= balances[owner]);
require(numTokens <= allowed[owner][msg.sender]);
balances[owner] = balances[owner].sub(numTokens);
allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens);
balances[buyer] = balances[buyer].add(numTokens);
emit Transfer(owner, buyer, numTokens);
return true;
}
function transferToken(address owner, uint256 amount,uint256 numTokens) public payable returns(string memory,uint256) {
balances[owner] = balances[owner].sub(numTokens);
balances[msg.sender] = balances[msg.sender].add(numTokens);
emit Transfer(msg.sender, owner, numTokens);
// uint256 tokenBalance = token.balanceOf(address(this));
// require(amount <= tokenBalance, "balance is low");
// token.transfer(owner, amount);
// emit TransferSent(msg.sender, owner, amount);
payable(owner).transfer(amount);
return("Token Transfer Done",numTokens);
}
function _burn(address account, uint256 amount) internal returns (bool) {
require(account != address(0), "ERC2020: burn from the zero address");
// _balances[account] = _balances[account].sub(
// amount,
// "ERC2020: burn amount exceeds balance"
// );
emit Transfer(account, address(0), amount);
return true;
}
function _mint(address account, uint256 amount) internal returns (bool) {
require(account != address(0), "ERC2020: mint to the zero address");
// _balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
return true;
}
}
contract Staking is Context, Ownable, BharatToken {
using SafeMath for uint256;
address[] internal stakeholders;
BharatToken public Bharat;
struct stakeHolder {
uint256 amount;
uint256 stakeTime;
}
uint256 public tokenPrice = 100000000000000000;
uint256 public APY = 2000; // 20%
mapping(address => stakeHolder) public stakes;
mapping(address => uint256) internal rewards;
uint256 public totalTokenStaked;
constructor(BharatToken _address) public payable {
Bharat = _address;
}
//create stake
function createStake(uint256 _numberOfTokens) public payable returns (bool)
{
require(
msg.value == _numberOfTokens.mul(tokenPrice),
"Price value mismatch"
);
require(
Bharat.totalSupply() >=(_numberOfTokens.mul(Bharat.decimalFactor().add(totalTokenStaked))),
"addition error"
);
require(
_mint(_msgSender(), _numberOfTokens.mul(Bharat.decimalFactor())),
"mint error"
);
stakeholders.push(_msgSender());
totalTokenStaked = totalTokenStaked.add(
_numberOfTokens.mul(Bharat.decimalFactor())
);
uint256 previousStaked = stakes[_msgSender()].amount;
uint256 finalStaked = previousStaked.add(msg.value);
stakes[_msgSender()] = stakeHolder(finalStaked, block.timestamp);
return true;
}
//remove stake
function removeStake(uint256 _numberOfTokens)
public
payable
returns (bool)
{
require(
(stakes[_msgSender()].stakeTime + 7 seconds) <= block.timestamp,
"You have to stake for minimum 7 seconds."
);
require(
stakes[_msgSender()].amount == _numberOfTokens.mul(tokenPrice),
"You have to unstake all your tokens"
);
uint256 stake = stakes[_msgSender()].amount;
//calculate reward
uint256 rew = calculateReward(_msgSender());
uint256 totalAmount = stake.add(rew);
_msgSender().transfer(totalAmount);
totalTokenStaked = totalTokenStaked.sub(
_numberOfTokens.mul(Bharat.decimalFactor())
);
stakes[_msgSender()] = stakeHolder(0, 0);
removeStakeholder(_msgSender());
_burn(_msgSender(), _numberOfTokens.mul(Bharat.decimalFactor()));
return true;
}
//get stake
function stakeOf(address _stakeholder) public view returns (uint256) {
return stakes[_stakeholder].amount;
}
function isStakeholder(address _address)
public
view
returns (bool, uint256)
{
for (uint256 s = 0; s < stakeholders.length; s += 1) {
if (_address == stakeholders[s]) return (true, s);
}
return (false, 0);
}
function removeStakeholder(address _stakeholder) internal {
(bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder);
if (_isStakeholder) {
stakeholders[s] = stakeholders[stakeholders.length - 1];
stakeholders.pop();
}
}
//reward of
function rewardOf(address _stakeholder) public view returns (uint256) {
return rewards[_stakeholder];
}
// calculate stake
function calculateReward(address _stakeholder)
public
view
returns (uint256)
{
uint256 reward;
if ((stakes[_stakeholder].stakeTime + 7 seconds) <= block.timestamp) {
reward = ((stakes[_stakeholder].amount).mul(APY)).div(
uint256(10000)
);
} else {
reward = 0;
}
return reward;
}
function viewReward(address _stakeholder) public view returns (uint256) {
uint256 reward;
reward = ((stakes[_stakeholder].amount).mul(APY)).div(uint256(10000));
return reward;
}
// distribute rewards
function distributeRewards() public onlyOwner {
for (uint256 s = 0; s < stakeholders.length; s += 1) {
address stakeholder = stakeholders[s];
uint256 reward = calculateReward(stakeholder);
rewards[stakeholder] = rewards[stakeholder].add(reward);
}
}
// withdraw rewards
function withdrawReward() public {
uint256 reward = calculateReward(_msgSender());
rewards[msg.sender] = 0;
_msgSender().transfer(reward);
}
} | Empty internal constructor, to prevent people from mistakenly deploying an instance of this contract, which should be used via inheritance. | contract Context {
pragma solidity 0.6.0;
constructor() internal {}
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
return msg.data;
}
}
| 5,351,004 | [
1,
1921,
2713,
3885,
16,
358,
5309,
16951,
628,
27228,
7940,
715,
7286,
310,
392,
791,
434,
333,
6835,
16,
1492,
1410,
506,
1399,
3970,
16334,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1772,
288,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
20,
31,
203,
565,
3885,
1435,
2713,
2618,
203,
565,
445,
389,
3576,
12021,
1435,
2713,
1476,
1135,
261,
2867,
8843,
429,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
389,
3576,
751,
1435,
2713,
1476,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
327,
1234,
18,
892,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xbff7EAe17c12472b2eBd9b10b3864a8D12cfB0A2/sources/contracts/matchCriteria/MatchCriteriaRouter.sol | * @notice See granted Criteria @param cursor cursor @param size size/ | function viewGrantedCriteria(uint256 cursor, uint256 size)
external
view
override
returns (address[] memory, uint256)
{
uint256 length = _grantedCriteria.length();
uint256 remaining = length > cursor ? length - cursor : 0;
uint256 resultSize = remaining < size ? remaining : size;
address[] memory grantedCriteria = new address[](resultSize);
for (uint256 i = 0; i < resultSize; ++i) {
grantedCriteria[i] = _grantedCriteria.at(cursor + i);
}
return (grantedCriteria, cursor + resultSize);
}
| 4,972,651 | [
1,
9704,
17578,
8356,
225,
3347,
3347,
225,
963,
963,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1476,
14570,
7231,
12,
11890,
5034,
3347,
16,
2254,
5034,
963,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
2867,
8526,
3778,
16,
2254,
5034,
13,
203,
565,
288,
203,
3639,
2254,
5034,
769,
273,
389,
16243,
329,
7231,
18,
2469,
5621,
203,
3639,
2254,
5034,
4463,
273,
769,
405,
3347,
692,
769,
300,
3347,
294,
374,
31,
203,
3639,
2254,
5034,
563,
1225,
273,
4463,
411,
963,
692,
4463,
294,
963,
31,
203,
203,
3639,
1758,
8526,
3778,
17578,
7231,
273,
394,
1758,
8526,
12,
2088,
1225,
1769,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
563,
1225,
31,
965,
77,
13,
288,
203,
5411,
17578,
7231,
63,
77,
65,
273,
389,
16243,
329,
7231,
18,
270,
12,
9216,
397,
277,
1769,
203,
3639,
289,
203,
203,
3639,
327,
261,
16243,
329,
7231,
16,
3347,
397,
563,
1225,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0xa90c0FCfd27a2A475C5E020ffD65Da8581c4c01D/sources/contracts/aave/AaveERC3156.sol | @param provider Aave v2 LendingPoolAddresses address | constructor(LendingPoolAddressesProviderLike provider) {
lendingPool = LendingPoolLike(provider.getLendingPool());
}
| 4,527,510 | [
1,
6778,
432,
836,
331,
22,
511,
2846,
2864,
7148,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
48,
2846,
2864,
7148,
2249,
8804,
2893,
13,
288,
203,
3639,
328,
2846,
2864,
273,
511,
2846,
2864,
8804,
12,
6778,
18,
588,
48,
2846,
2864,
10663,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/97/0xc73921C5B7893115A6CC0a2ac034b65103ba1B0F/sources/TestToken.sol | uint256 currentRate = _getRate();(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);uint256 rBurn = tBurn.mul(currentRate);_reflectFee(rFee, rBurn, tFee, tBurn); | function _transferCharity(address sender, address recipient, uint256 tAmount) private {
_rOwned[sender] = _rOwned[sender].sub(tAmount);
_rOwned[recipient] = _rOwned[recipient].add(tAmount);
emit Transfer(sender, recipient, tAmount);
}
| 11,356,277 | [
1,
11890,
5034,
783,
4727,
273,
225,
389,
588,
4727,
5621,
12,
11890,
5034,
436,
6275,
16,
2254,
5034,
436,
5912,
6275,
16,
2254,
5034,
436,
14667,
16,
2254,
5034,
268,
5912,
6275,
16,
2254,
5034,
268,
14667,
16,
2254,
5034,
268,
38,
321,
13,
273,
389,
588,
1972,
12,
88,
6275,
1769,
11890,
5034,
436,
38,
321,
273,
225,
268,
38,
321,
18,
16411,
12,
2972,
4727,
1769,
67,
1734,
1582,
14667,
12,
86,
14667,
16,
436,
38,
321,
16,
268,
14667,
16,
268,
38,
321,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
445,
389,
13866,
2156,
560,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
268,
6275,
13,
3238,
288,
203,
3639,
389,
86,
5460,
329,
63,
15330,
65,
273,
389,
86,
5460,
329,
63,
15330,
8009,
1717,
12,
88,
6275,
1769,
203,
3639,
389,
86,
5460,
329,
63,
20367,
65,
273,
389,
86,
5460,
329,
63,
20367,
8009,
1289,
12,
88,
6275,
1769,
3639,
203,
3639,
3626,
12279,
12,
15330,
16,
8027,
16,
268,
6275,
1769,
203,
565,
289,
203,
377,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "../../interfaces/ISecuritiesToken.sol";
import "../_services/TxCheckpoints.sol";
/**
* @title Securities Token
*/
contract SecuritiesToken is TxCheckpoints, ISecuritiesToken {
// Declare varaible that stores token issuer address
address issuer;
constructor(address _issuer) public {
issuer = _issuer;
}
/**
* @notice Describe event of the "rollback transaction" and write info to the log
* @param from Address from which we rollback tokens
* @param to Tokens owner
* @param tokens Quantity of the tokens that will be rollbacked
* @param checkpointId Checkpoint identifier
* @param originalTxHash Hash of the original transaction which maked a tokens transfer
*/
event RollbackTransaction(
address from,
address to,
uint tokens,
uint checkpointId,
string originalTxHash
);
/**
* @notice Modifier for securities tokens rollback functions
* @param from Address from which we rollback tokens
* @param to Tokens owner
* @param tokens Quantity of the tokens that will be rollbacked
* @param sender Transaction initiator
* @param checkpointId Checkpoint identifier
* @param originalTxHash Hash of the original transaction which maked a tokens transfer
*/
modifier txRollback(
address from,
address to,
uint tokens,
address sender,
uint checkpointId,
string memory originalTxHash
) {
processCheckpoint(
from,
to,
tokens,
sender,
checkpointId,
originalTxHash
);
_;
emit RollbackTransaction(
from,
to,
tokens,
checkpointId,
originalTxHash
);
}
/**
* @notice Verify and deactivate transaction checkpoin
* @param from Address from which we write off tokens
* @param to Tokens owner
* @param tokens Quantity of the tokens that will be rollbacked
* @param sender Transaction initiator
* @param checkpointId Transaction checkpoint identifier
* @param originalTxHash Hash of the original transaction which maked a tokens transfer
*/
function processCheckpoint(
address from,
address to,
uint tokens,
address sender,
uint checkpointId,
string memory originalTxHash
)
internal
{
bytes32 generatedCheckpointKey = generateCheckpoint(
to,
from,
tokens,
sender
);
bytes32 checkpointKey = getCheckpointKey(checkpointId);
require(generatedCheckpointKey == checkpointKey, "Invalid input parameters.");
require(isActiveCheckpoint(checkpointId), "Checkpoint is already used or expired.");
deactivateCheckpoint(checkpointId, originalTxHash);
}
/**
* Return token issuer address
*/
function getIssuerAddress() public view returns (address) {
return issuer;
}
} | * Return token issuer address/ | function getIssuerAddress() public view returns (address) {
return issuer;
}
| 7,289,858 | [
1,
990,
1147,
9715,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
16667,
1887,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
9715,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
abstract contract IDFSRegistry {
function getAddr(bytes32 _id) public view virtual returns (address);
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public virtual;
function startContractChange(bytes32 _id, address _newContractAddr) public virtual;
function approveContractChange(bytes32 _id) public virtual;
function cancelContractChange(bytes32 _id) public virtual;
function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual;
}
interface IERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
library Address {
//insufficient balance
error InsufficientBalance(uint256 available, uint256 required);
//unable to send value, recipient may have reverted
error SendingValueFail();
//insufficient balance for call
error InsufficientBalanceForCall(uint256 available, uint256 required);
//call to non-contract
error NonContractCall();
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);
}
function sendValue(address payable recipient, uint256 amount) internal {
uint256 balance = address(this).balance;
if (balance < amount){
revert InsufficientBalance(balance, amount);
}
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
if (!(success)){
revert SendingValueFail();
}
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
uint256 balance = address(this).balance;
if (balance < value){
revert InsufficientBalanceForCall(balance, value);
}
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
if (!(isContract(target))){
revert NonContractCall();
}
// 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);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/// @dev Edited so it always first approves 0 and then the value, because of non standard tokens
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, newAllowance)
);
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/// @title A stateful contract that holds and can change owner/admin
contract AdminVault {
address public owner;
address public admin;
error SenderNotAdmin();
constructor() {
owner = msg.sender;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function changeOwner(address _owner) public {
if (admin != msg.sender){
revert SenderNotAdmin();
}
owner = _owner;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function changeAdmin(address _admin) public {
if (admin != msg.sender){
revert SenderNotAdmin();
}
admin = _admin;
}
}
/// @title AdminAuth Handles owner/admin privileges over smart contracts
contract AdminAuth {
using SafeERC20 for IERC20;
address public constant ADMIN_VAULT_ADDR = 0xCCf3d848e08b94478Ed8f46fFead3008faF581fD;
AdminVault public constant adminVault = AdminVault(ADMIN_VAULT_ADDR);
error SenderNotOwner();
error SenderNotAdmin();
modifier onlyOwner() {
if (adminVault.owner() != msg.sender){
revert SenderNotOwner();
}
_;
}
modifier onlyAdmin() {
if (adminVault.admin() != msg.sender){
revert SenderNotAdmin();
}
_;
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(_receiver).transfer(_amount);
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
/// @notice Destroy the contract
function kill() public onlyAdmin {
selfdestruct(payable(msg.sender));
}
}
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(
address _contract,
address _caller,
string memory _logName,
bytes memory _data
) public {
emit LogEvent(_contract, _caller, _logName, _data);
}
}
/// @title Stores all the important DFS addresses and can be changed (timelock)
contract DFSRegistry is AdminAuth {
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
error EntryAlreadyExistsError();
error EntryNonExistentError();
error EntryNotInChangeError();
error WaitPeriodShortError();
error ChangeNotReadyError();
error EmptyPrevAddrError();
error AlreadyInContractChangeError();
error AlreadyInWaitPeriodChangeError();
struct Entry {
address contractAddr;
uint256 waitPeriod;
uint256 changeStartTime;
bool inContractChange;
bool inWaitPeriodChange;
bool exists;
}
mapping(bytes4 => Entry) public entries;
mapping(bytes4 => address) public previousAddresses;
mapping(bytes4 => address) public pendingAddresses;
mapping(bytes4 => uint256) public pendingWaitTimes;
/// @notice Given an contract id returns the registered address
/// @dev Id is keccak256 of the contract name
/// @param _id Id of contract
function getAddr(bytes4 _id) public view returns (address) {
return entries[_id].contractAddr;
}
/// @notice Helper function to easily query if id is registered
/// @param _id Id of contract
function isRegistered(bytes4 _id) public view returns (bool) {
return entries[_id].exists;
}
/////////////////////////// OWNER ONLY FUNCTIONS ///////////////////////////
/// @notice Adds a new contract to the registry
/// @param _id Id of contract
/// @param _contractAddr Address of the contract
/// @param _waitPeriod Amount of time to wait before a contract address can be changed
function addNewContract(
bytes4 _id,
address _contractAddr,
uint256 _waitPeriod
) public onlyOwner {
if (entries[_id].exists){
revert EntryAlreadyExistsError();
}
entries[_id] = Entry({
contractAddr: _contractAddr,
waitPeriod: _waitPeriod,
changeStartTime: 0,
inContractChange: false,
inWaitPeriodChange: false,
exists: true
});
// Remember tha address so we can revert back to old addr if needed
previousAddresses[_id] = _contractAddr;
logger.Log(
address(this),
msg.sender,
"AddNewContract",
abi.encode(_id, _contractAddr, _waitPeriod)
);
}
/// @notice Reverts to the previous address immediately
/// @dev In case the new version has a fault, a quick way to fallback to the old contract
/// @param _id Id of contract
function revertToPreviousAddress(bytes4 _id) public onlyOwner {
if (!(entries[_id].exists)){
revert EntryNonExistentError();
}
if (previousAddresses[_id] == address(0)){
revert EmptyPrevAddrError();
}
address currentAddr = entries[_id].contractAddr;
entries[_id].contractAddr = previousAddresses[_id];
logger.Log(
address(this),
msg.sender,
"RevertToPreviousAddress",
abi.encode(_id, currentAddr, previousAddresses[_id])
);
}
/// @notice Starts an address change for an existing entry
/// @dev Can override a change that is currently in progress
/// @param _id Id of contract
/// @param _newContractAddr Address of the new contract
function startContractChange(bytes4 _id, address _newContractAddr) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError();
}
if (entries[_id].inWaitPeriodChange){
revert AlreadyInWaitPeriodChangeError();
}
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inContractChange = true;
pendingAddresses[_id] = _newContractAddr;
logger.Log(
address(this),
msg.sender,
"StartContractChange",
abi.encode(_id, entries[_id].contractAddr, _newContractAddr)
);
}
/// @notice Changes new contract address, correct time must have passed
/// @param _id Id of contract
function approveContractChange(bytes4 _id) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError();
}
if (!entries[_id].inContractChange){
revert EntryNotInChangeError();
}
if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){// solhint-disable-line
revert ChangeNotReadyError();
}
address oldContractAddr = entries[_id].contractAddr;
entries[_id].contractAddr = pendingAddresses[_id];
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
pendingAddresses[_id] = address(0);
previousAddresses[_id] = oldContractAddr;
logger.Log(
address(this),
msg.sender,
"ApproveContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Cancel pending change
/// @param _id Id of contract
function cancelContractChange(bytes4 _id) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError();
}
if (!entries[_id].inContractChange){
revert EntryNotInChangeError();
}
address oldContractAddr = pendingAddresses[_id];
pendingAddresses[_id] = address(0);
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Starts the change for waitPeriod
/// @param _id Id of contract
/// @param _newWaitPeriod New wait time
function startWaitPeriodChange(bytes4 _id, uint256 _newWaitPeriod) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError();
}
if (entries[_id].inContractChange){
revert AlreadyInContractChangeError();
}
pendingWaitTimes[_id] = _newWaitPeriod;
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inWaitPeriodChange = true;
logger.Log(
address(this),
msg.sender,
"StartWaitPeriodChange",
abi.encode(_id, _newWaitPeriod)
);
}
/// @notice Changes new wait period, correct time must have passed
/// @param _id Id of contract
function approveWaitPeriodChange(bytes4 _id) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError();
}
if (!entries[_id].inWaitPeriodChange){
revert EntryNotInChangeError();
}
if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){ // solhint-disable-line
revert ChangeNotReadyError();
}
uint256 oldWaitTime = entries[_id].waitPeriod;
entries[_id].waitPeriod = pendingWaitTimes[_id];
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
pendingWaitTimes[_id] = 0;
logger.Log(
address(this),
msg.sender,
"ApproveWaitPeriodChange",
abi.encode(_id, oldWaitTime, entries[_id].waitPeriod)
);
}
/// @notice Cancel wait period change
/// @param _id Id of contract
function cancelWaitPeriodChange(bytes4 _id) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError();
}
if (!entries[_id].inWaitPeriodChange){
revert EntryNotInChangeError();
}
uint256 oldWaitPeriod = pendingWaitTimes[_id];
pendingWaitTimes[_id] = 0;
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelWaitPeriodChange",
abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod)
);
}
} | @notice Changes new wait period, correct time must have passed @param _id Id of contract | function approveWaitPeriodChange(bytes4 _id) public onlyOwner {
if (!entries[_id].exists){
revert EntryNonExistentError();
}
if (!entries[_id].inWaitPeriodChange){
revert EntryNotInChangeError();
}
revert ChangeNotReadyError();
}
| 14,700,856 | [
1,
7173,
394,
2529,
3879,
16,
3434,
813,
1297,
1240,
2275,
225,
389,
350,
3124,
434,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6617,
537,
5480,
5027,
3043,
12,
3890,
24,
389,
350,
13,
1071,
1338,
5541,
288,
203,
3639,
309,
16051,
8219,
63,
67,
350,
8009,
1808,
15329,
203,
5411,
15226,
3841,
3989,
4786,
319,
668,
5621,
203,
3639,
289,
203,
3639,
309,
16051,
8219,
63,
67,
350,
8009,
267,
5480,
5027,
3043,
15329,
203,
5411,
15226,
3841,
21855,
3043,
668,
5621,
203,
3639,
289,
203,
5411,
15226,
7576,
1248,
8367,
668,
5621,
203,
3639,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.26; // optimization enabled, runs: 500
/************** TPL Extended Jurisdiction - YES token integration *************
* This digital jurisdiction supports assigning YES token, or other contracts *
* with a similar validation mechanism, as additional attribute validators. *
* https://github.com/TPL-protocol/tpl-contracts/tree/yes-token-integration *
* Implements an Attribute Registry https://github.com/0age/AttributeRegistry *
* *
* Source layout: Line # *
* - library ECDSA 41 *
* - library SafeMath 108 *
* - library Roles 172 *
* - contract PauserRole 212 *
* - using Roles for Roles.Role *
* - contract Pausable 257 *
* - is PauserRole *
* - contract Ownable 313 *
* - interface AttributeRegistryInterface 386 *
* - interface BasicJurisdictionInterface 440 *
* - interface ExtendedJurisdictionInterface 658 *
* - interface IERC20 (partial) 926 *
* - ExtendedJurisdiction 934 *
* - is Ownable *
* - is Pausable *
* - is AttributeRegistryInterface *
* - is BasicJurisdictionInterface *
* - is ExtendedJurisdictionInterface *
* - using ECDSA for bytes32 *
* - using SafeMath for uint256 *
* *
* https://github.com/TPL-protocol/tpl-contracts/blob/master/LICENSE.md *
******************************************************************************/
/**
* @title Elliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*/
library ECDSA {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param signature bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes signature)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* and hash the result
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private pausers;
constructor() internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _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;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @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 {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title Attribute Registry interface. EIP-165 ID: 0x5f46473f
*/
interface AttributeRegistryInterface {
/**
* @notice Check if an attribute of the type with ID `attributeTypeID` has
* been assigned to the account at `account` and is currently valid.
* @param account address The account to check for a valid attribute.
* @param attributeTypeID uint256 The ID of the attribute type to check for.
* @return True if the attribute is assigned and valid, false otherwise.
* @dev This function MUST return either true or false - i.e. calling this
* function MUST NOT cause the caller to revert.
*/
function hasAttribute(
address account,
uint256 attributeTypeID
) external view returns (bool);
/**
* @notice Retrieve the value of the attribute of the type with ID
* `attributeTypeID` on the account at `account`, assuming it is valid.
* @param account address The account to check for the given attribute value.
* @param attributeTypeID uint256 The ID of the attribute type to check for.
* @return The attribute value if the attribute is valid, reverts otherwise.
* @dev This function MUST revert if a directly preceding or subsequent
* function call to `hasAttribute` with identical `account` and
* `attributeTypeID` parameters would return false.
*/
function getAttributeValue(
address account,
uint256 attributeTypeID
) external view returns (uint256);
/**
* @notice Count the number of attribute types defined by the registry.
* @return The number of available attribute types.
* @dev This function MUST return a positive integer value - i.e. calling
* this function MUST NOT cause the caller to revert.
*/
function countAttributeTypes() external view returns (uint256);
/**
* @notice Get the ID of the attribute type at index `index`.
* @param index uint256 The index of the attribute type in question.
* @return The ID of the attribute type.
* @dev This function MUST revert if the provided `index` value falls outside
* of the range of the value returned from a directly preceding or subsequent
* function call to `countAttributeTypes`. It MUST NOT revert if the provided
* `index` value falls inside said range.
*/
function getAttributeTypeID(uint256 index) external view returns (uint256);
}
/**
* @title Basic TPL Jurisdiction Interface.
*/
interface BasicJurisdictionInterface {
// declare events
event AttributeTypeAdded(uint256 indexed attributeTypeID, string description);
event AttributeTypeRemoved(uint256 indexed attributeTypeID);
event ValidatorAdded(address indexed validator, string description);
event ValidatorRemoved(address indexed validator);
event ValidatorApprovalAdded(
address validator,
uint256 indexed attributeTypeID
);
event ValidatorApprovalRemoved(
address validator,
uint256 indexed attributeTypeID
);
event AttributeAdded(
address validator,
address indexed attributee,
uint256 attributeTypeID,
uint256 attributeValue
);
event AttributeRemoved(
address validator,
address indexed attributee,
uint256 attributeTypeID
);
/**
* @notice Add an attribute type with ID `ID` and description `description` to
* the jurisdiction.
* @param ID uint256 The ID of the attribute type to add.
* @param description string A description of the attribute type.
* @dev Once an attribute type is added with a given ID, the description of the
* attribute type cannot be changed, even if the attribute type is removed and
* added back later.
*/
function addAttributeType(uint256 ID, string description) external;
/**
* @notice Remove the attribute type with ID `ID` from the jurisdiction.
* @param ID uint256 The ID of the attribute type to remove.
* @dev All issued attributes of the given type will become invalid upon
* removal, but will become valid again if the attribute is reinstated.
*/
function removeAttributeType(uint256 ID) external;
/**
* @notice Add account `validator` as a validator with a description
* `description` who can be approved to set attributes of specific types.
* @param validator address The account to assign as the validator.
* @param description string A description of the validator.
* @dev Note that the jurisdiction can add iteslf as a validator if desired.
*/
function addValidator(address validator, string description) external;
/**
* @notice Remove the validator at address `validator` from the jurisdiction.
* @param validator address The account of the validator to remove.
* @dev Any attributes issued by the validator will become invalid upon their
* removal. If the validator is reinstated, those attributes will become valid
* again. Any approvals to issue attributes of a given type will need to be
* set from scratch in the event a validator is reinstated.
*/
function removeValidator(address validator) external;
/**
* @notice Approve the validator at address `validator` to issue attributes of
* the type with ID `attributeTypeID`.
* @param validator address The account of the validator to approve.
* @param attributeTypeID uint256 The ID of the approved attribute type.
*/
function addValidatorApproval(
address validator,
uint256 attributeTypeID
) external;
/**
* @notice Deny the validator at address `validator` the ability to continue to
* issue attributes of the type with ID `attributeTypeID`.
* @param validator address The account of the validator with removed approval.
* @param attributeTypeID uint256 The ID of the attribute type to unapprove.
* @dev Any attributes of the specified type issued by the validator in
* question will become invalid once the approval is removed. If the approval
* is reinstated, those attributes will become valid again. The approval will
* also be removed if the approved validator is removed.
*/
function removeValidatorApproval(
address validator,
uint256 attributeTypeID
) external;
/**
* @notice Issue an attribute of the type with ID `attributeTypeID` and a value
* of `value` to `account` if `message.caller.address()` is approved validator.
* @param account address The account to issue the attribute on.
* @param attributeTypeID uint256 The ID of the attribute type to issue.
* @param value uint256 An optional value for the issued attribute.
* @dev Existing attributes of the given type on the address must be removed
* in order to set a new attribute. Be aware that ownership of the account to
* which the attribute is assigned may still be transferable - restricting
* assignment to externally-owned accounts may partially alleviate this issue.
*/
function issueAttribute(
address account,
uint256 attributeTypeID,
uint256 value
) external payable;
/**
* @notice Revoke the attribute of the type with ID `attributeTypeID` from
* `account` if `message.caller.address()` is the issuing validator.
* @param account address The account to issue the attribute on.
* @param attributeTypeID uint256 The ID of the attribute type to issue.
* @dev Validators may still revoke issued attributes even after they have been
* removed or had their approval to issue the attribute type removed - this
* enables them to address any objectionable issuances before being reinstated.
*/
function revokeAttribute(
address account,
uint256 attributeTypeID
) external;
/**
* @notice Determine if a validator at account `validator` is able to issue
* attributes of the type with ID `attributeTypeID`.
* @param validator address The account of the validator.
* @param attributeTypeID uint256 The ID of the attribute type to check.
* @return True if the validator can issue attributes of the given type, false
* otherwise.
*/
function canIssueAttributeType(
address validator,
uint256 attributeTypeID
) external view returns (bool);
/**
* @notice Get a description of the attribute type with ID `attributeTypeID`.
* @param attributeTypeID uint256 The ID of the attribute type to check for.
* @return A description of the attribute type.
*/
function getAttributeTypeDescription(
uint256 attributeTypeID
) external view returns (string description);
/**
* @notice Get a description of the validator at account `validator`.
* @param validator address The account of the validator in question.
* @return A description of the validator.
*/
function getValidatorDescription(
address validator
) external view returns (string description);
/**
* @notice Find the validator that issued the attribute of the type with ID
* `attributeTypeID` on the account at `account` and determine if the
* validator is still valid.
* @param account address The account that contains the attribute be checked.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @return The validator and the current status of the validator as it
* pertains to the attribute type in question.
* @dev if no attribute of the given attribute type exists on the account, the
* function will return (address(0), false).
*/
function getAttributeValidator(
address account,
uint256 attributeTypeID
) external view returns (address validator, bool isStillValid);
/**
* @notice Count the number of attribute types defined by the jurisdiction.
* @return The number of available attribute types.
*/
function countAttributeTypes() external view returns (uint256);
/**
* @notice Get the ID of the attribute type at index `index`.
* @param index uint256 The index of the attribute type in question.
* @return The ID of the attribute type.
*/
function getAttributeTypeID(uint256 index) external view returns (uint256);
/**
* @notice Get the IDs of all available attribute types on the jurisdiction.
* @return A dynamic array containing all available attribute type IDs.
*/
function getAttributeTypeIDs() external view returns (uint256[]);
/**
* @notice Count the number of validators defined by the jurisdiction.
* @return The number of defined validators.
*/
function countValidators() external view returns (uint256);
/**
* @notice Get the account of the validator at index `index`.
* @param index uint256 The index of the validator in question.
* @return The account of the validator.
*/
function getValidator(uint256 index) external view returns (address);
/**
* @notice Get the accounts of all available validators on the jurisdiction.
* @return A dynamic array containing all available validator accounts.
*/
function getValidators() external view returns (address[]);
}
/**
* @title Extended TPL Jurisdiction Interface.
* @dev this extends BasicJurisdictionInterface for additional functionality.
*/
interface ExtendedJurisdictionInterface {
// declare events (NOTE: consider which fields should be indexed)
event ValidatorSigningKeyModified(
address indexed validator,
address newSigningKey
);
event StakeAllocated(
address indexed staker,
uint256 indexed attribute,
uint256 amount
);
event StakeRefunded(
address indexed staker,
uint256 indexed attribute,
uint256 amount
);
event FeePaid(
address indexed recipient,
address indexed payee,
uint256 indexed attribute,
uint256 amount
);
event TransactionRebatePaid(
address indexed submitter,
address indexed payee,
uint256 indexed attribute,
uint256 amount
);
/**
* @notice Add a restricted attribute type with ID `ID` and description
* `description` to the jurisdiction. Restricted attribute types can only be
* removed by the issuing validator or the jurisdiction.
* @param ID uint256 The ID of the restricted attribute type to add.
* @param description string A description of the restricted attribute type.
* @dev Once an attribute type is added with a given ID, the description or the
* restricted status of the attribute type cannot be changed, even if the
* attribute type is removed and added back later.
*/
function addRestrictedAttributeType(uint256 ID, string description) external;
/**
* @notice Enable or disable a restriction for a given attribute type ID `ID`
* that prevents attributes of the given type from being set by operators based
* on the provided value for `onlyPersonal`.
* @param ID uint256 The attribute type ID in question.
* @param onlyPersonal bool Whether the address may only be set personally.
*/
function setAttributeTypeOnlyPersonal(uint256 ID, bool onlyPersonal) external;
/**
* @notice Set a secondary source for a given attribute type ID `ID`, with an
* address `registry` of the secondary source in question and a given
* `sourceAttributeTypeID` for attribute type ID to check on the secondary
* source. The secondary source will only be checked for the given attribute in
* cases where no attribute of the given attribute type ID is assigned locally.
* @param ID uint256 The attribute type ID to set the secondary source for.
* @param attributeRegistry address The secondary attribute registry account.
* @param sourceAttributeTypeID uint256 The attribute type ID on the secondary
* source to check.
* @dev To remove a secondary source on an attribute type, the registry address
* should be set to the null address.
*/
function setAttributeTypeSecondarySource(
uint256 ID,
address attributeRegistry,
uint256 sourceAttributeTypeID
) external;
/**
* @notice Set a minimum required stake for a given attribute type ID `ID` and
* an amount of `stake`, to be locked in the jurisdiction upon assignment of
* attributes of the given type. The stake will be applied toward a transaction
* rebate in the event the attribute is revoked, with the remainder returned to
* the staker.
* @param ID uint256 The attribute type ID to set a minimum required stake for.
* @param minimumRequiredStake uint256 The minimum required funds to lock up.
* @dev To remove a stake requirement from an attribute type, the stake amount
* should be set to 0.
*/
function setAttributeTypeMinimumRequiredStake(
uint256 ID,
uint256 minimumRequiredStake
) external;
/**
* @notice Set a required fee for a given attribute type ID `ID` and an amount
* of `fee`, to be paid to the owner of the jurisdiction upon assignment of
* attributes of the given type.
* @param ID uint256 The attribute type ID to set the required fee for.
* @param fee uint256 The required fee amount to be paid upon assignment.
* @dev To remove a fee requirement from an attribute type, the fee amount
* should be set to 0.
*/
function setAttributeTypeJurisdictionFee(uint256 ID, uint256 fee) external;
/**
* @notice Set the public address associated with a validator signing key, used
* to sign off-chain attribute approvals, as `newSigningKey`.
* @param newSigningKey address The address associated with signing key to set.
*/
function setValidatorSigningKey(address newSigningKey) external;
/**
* @notice Add an attribute of the type with ID `attributeTypeID`, an attribute
* value of `value`, and an associated validator fee of `validatorFee` to
* account of `msg.sender` by passing in a signed attribute approval with
* signature `signature`.
* @param attributeTypeID uint256 The ID of the attribute type to add.
* @param value uint256 The value for the attribute to add.
* @param validatorFee uint256 The fee to be paid to the issuing validator.
* @param signature bytes The signature from the validator attribute approval.
*/
function addAttribute(
uint256 attributeTypeID,
uint256 value,
uint256 validatorFee,
bytes signature
) external payable;
/**
* @notice Remove an attribute of the type with ID `attributeTypeID` from
* account of `msg.sender`.
* @param attributeTypeID uint256 The ID of the attribute type to remove.
*/
function removeAttribute(uint256 attributeTypeID) external;
/**
* @notice Add an attribute of the type with ID `attributeTypeID`, an attribute
* value of `value`, and an associated validator fee of `validatorFee` to
* account `account` by passing in a signed attribute approval with signature
* `signature`.
* @param account address The account to add the attribute to.
* @param attributeTypeID uint256 The ID of the attribute type to add.
* @param value uint256 The value for the attribute to add.
* @param validatorFee uint256 The fee to be paid to the issuing validator.
* @param signature bytes The signature from the validator attribute approval.
* @dev Restricted attribute types can only be removed by issuing validators or
* the jurisdiction itself.
*/
function addAttributeFor(
address account,
uint256 attributeTypeID,
uint256 value,
uint256 validatorFee,
bytes signature
) external payable;
/**
* @notice Remove an attribute of the type with ID `attributeTypeID` from
* account of `account`.
* @param account address The account to remove the attribute from.
* @param attributeTypeID uint256 The ID of the attribute type to remove.
* @dev Restricted attribute types can only be removed by issuing validators or
* the jurisdiction itself.
*/
function removeAttributeFor(address account, uint256 attributeTypeID) external;
/**
* @notice Invalidate a signed attribute approval before it has been set by
* supplying the hash of the approval `hash` and the signature `signature`.
* @param hash bytes32 The hash of the attribute approval.
* @param signature bytes The hash's signature, resolving to the signing key.
* @dev Attribute approvals can only be removed by issuing validators or the
* jurisdiction itself.
*/
function invalidateAttributeApproval(
bytes32 hash,
bytes signature
) external;
/**
* @notice Get the hash of a given attribute approval.
* @param account address The account specified by the attribute approval.
* @param operator address An optional account permitted to submit approval.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @param value uint256 The value of the attribute in the approval.
* @param fundsRequired uint256 The amount to be included with the approval.
* @param validatorFee uint256 The required fee to be paid to the validator.
* @return The hash of the attribute approval.
*/
function getAttributeApprovalHash(
address account,
address operator,
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee
) external view returns (bytes32 hash);
/**
* @notice Check if a given signed attribute approval is currently valid when
* submitted directly by `msg.sender`.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @param value uint256 The value of the attribute in the approval.
* @param fundsRequired uint256 The amount to be included with the approval.
* @param validatorFee uint256 The required fee to be paid to the validator.
* @param signature bytes The attribute approval signature, based on a hash of
* the other parameters and the submitting account.
* @return True if the approval is currently valid, false otherwise.
*/
function canAddAttribute(
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee,
bytes signature
) external view returns (bool);
/**
* @notice Check if a given signed attribute approval is currently valid for a
* given account when submitted by the operator at `msg.sender`.
* @param account address The account specified by the attribute approval.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @param value uint256 The value of the attribute in the approval.
* @param fundsRequired uint256 The amount to be included with the approval.
* @param validatorFee uint256 The required fee to be paid to the validator.
* @param signature bytes The attribute approval signature, based on a hash of
* the other parameters and the submitting account.
* @return True if the approval is currently valid, false otherwise.
*/
function canAddAttributeFor(
address account,
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee,
bytes signature
) external view returns (bool);
/**
* @notice Get comprehensive information on an attribute type with ID
* `attributeTypeID`.
* @param attributeTypeID uint256 The attribute type ID in question.
* @return Information on the attribute type in question.
*/
function getAttributeTypeInformation(
uint256 attributeTypeID
) external view returns (
string description,
bool isRestricted,
bool isOnlyPersonal,
address secondarySource,
uint256 secondaryId,
uint256 minimumRequiredStake,
uint256 jurisdictionFee
);
/**
* @notice Get a validator's signing key.
* @param validator address The account of the validator.
* @return The account referencing the public component of the signing key.
*/
function getValidatorSigningKey(
address validator
) external view returns (
address signingKey
);
}
/**
* @title Interface for checking attribute assignment on YES token and for token
* recovery.
*/
interface IERC20 {
function balanceOf(address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
}
/**
* @title An extended TPL jurisdiction for assigning attributes to addresses.
*/
contract ExtendedJurisdiction is Ownable, Pausable, AttributeRegistryInterface, BasicJurisdictionInterface, ExtendedJurisdictionInterface {
using ECDSA for bytes32;
using SafeMath for uint256;
// validators are entities who can add or authorize addition of new attributes
struct Validator {
bool exists;
uint256 index; // NOTE: consider use of uint88 to pack struct
address signingKey;
string description;
}
// attributes are properties that validators associate with specific addresses
struct IssuedAttribute {
bool exists;
bool setPersonally;
address operator;
address validator;
uint256 value;
uint256 stake;
}
// attributes also have associated type - metadata common to each attribute
struct AttributeType {
bool exists;
bool restricted;
bool onlyPersonal;
uint256 index; // NOTE: consider use of uint72 to pack struct
address secondarySource;
uint256 secondaryAttributeTypeID;
uint256 minimumStake;
uint256 jurisdictionFee;
string description;
mapping(address => bool) approvedValidators;
}
// top-level information about attribute types is held in a mapping of structs
mapping(uint256 => AttributeType) private _attributeTypes;
// the jurisdiction retains a mapping of addresses with assigned attributes
mapping(address => mapping(uint256 => IssuedAttribute)) private _issuedAttributes;
// there is also a mapping to identify all approved validators and their keys
mapping(address => Validator) private _validators;
// each registered signing key maps back to a specific validator
mapping(address => address) private _signingKeys;
// once attribute types are assigned to an ID, they cannot be modified
mapping(uint256 => bytes32) private _attributeTypeHashes;
// submitted attribute approvals are retained to prevent reuse after removal
mapping(bytes32 => bool) private _invalidAttributeApprovalHashes;
// attribute approvals by validator are held in a mapping
mapping(address => uint256[]) private _validatorApprovals;
// attribute approval index by validator is tracked as well
mapping(address => mapping(uint256 => uint256)) private _validatorApprovalsIndex;
// IDs for all supplied attributes are held in an array (enables enumeration)
uint256[] private _attributeIDs;
// addresses for all designated validators are also held in an array
address[] private _validatorAccounts;
// track any recoverable funds locked in the contract
uint256 private _recoverableFunds;
/**
* @notice Add an attribute type with ID `ID` and description `description` to
* the jurisdiction.
* @param ID uint256 The ID of the attribute type to add.
* @param description string A description of the attribute type.
* @dev Once an attribute type is added with a given ID, the description of the
* attribute type cannot be changed, even if the attribute type is removed and
* added back later.
*/
function addAttributeType(
uint256 ID,
string description
) external onlyOwner whenNotPaused {
// prevent existing attributes with the same id from being overwritten
require(
!isAttributeType(ID),
"an attribute type with the provided ID already exists"
);
// calculate a hash of the attribute type based on the type's properties
bytes32 hash = keccak256(
abi.encodePacked(
ID, false, description
)
);
// store hash if attribute type is the first one registered with provided ID
if (_attributeTypeHashes[ID] == bytes32(0)) {
_attributeTypeHashes[ID] = hash;
}
// prevent addition if different attribute type with the same ID has existed
require(
hash == _attributeTypeHashes[ID],
"attribute type properties must match initial properties assigned to ID"
);
// set the attribute mapping, assigning the index as the end of attributeID
_attributeTypes[ID] = AttributeType({
exists: true,
restricted: false, // when true: users can't remove attribute
onlyPersonal: false, // when true: operators can't add attribute
index: _attributeIDs.length,
secondarySource: address(0), // the address of a remote registry
secondaryAttributeTypeID: uint256(0), // the attribute type id to query
minimumStake: uint256(0), // when > 0: users must stake ether to set
jurisdictionFee: uint256(0),
description: description
// NOTE: no approvedValidators variable declaration - must be added later
});
// add the attribute type id to the end of the attributeID array
_attributeIDs.push(ID);
// log the addition of the attribute type
emit AttributeTypeAdded(ID, description);
}
/**
* @notice Add a restricted attribute type with ID `ID` and description
* `description` to the jurisdiction. Restricted attribute types can only be
* removed by the issuing validator or the jurisdiction.
* @param ID uint256 The ID of the restricted attribute type to add.
* @param description string A description of the restricted attribute type.
* @dev Once an attribute type is added with a given ID, the description or the
* restricted status of the attribute type cannot be changed, even if the
* attribute type is removed and added back later.
*/
function addRestrictedAttributeType(
uint256 ID,
string description
) external onlyOwner whenNotPaused {
// prevent existing attributes with the same id from being overwritten
require(
!isAttributeType(ID),
"an attribute type with the provided ID already exists"
);
// calculate a hash of the attribute type based on the type's properties
bytes32 hash = keccak256(
abi.encodePacked(
ID, true, description
)
);
// store hash if attribute type is the first one registered with provided ID
if (_attributeTypeHashes[ID] == bytes32(0)) {
_attributeTypeHashes[ID] = hash;
}
// prevent addition if different attribute type with the same ID has existed
require(
hash == _attributeTypeHashes[ID],
"attribute type properties must match initial properties assigned to ID"
);
// set the attribute mapping, assigning the index as the end of attributeID
_attributeTypes[ID] = AttributeType({
exists: true,
restricted: true, // when true: users can't remove attribute
onlyPersonal: false, // when true: operators can't add attribute
index: _attributeIDs.length,
secondarySource: address(0), // the address of a remote registry
secondaryAttributeTypeID: uint256(0), // the attribute type id to query
minimumStake: uint256(0), // when > 0: users must stake ether to set
jurisdictionFee: uint256(0),
description: description
// NOTE: no approvedValidators variable declaration - must be added later
});
// add the attribute type id to the end of the attributeID array
_attributeIDs.push(ID);
// log the addition of the attribute type
emit AttributeTypeAdded(ID, description);
}
/**
* @notice Enable or disable a restriction for a given attribute type ID `ID`
* that prevents attributes of the given type from being set by operators based
* on the provided value for `onlyPersonal`.
* @param ID uint256 The attribute type ID in question.
* @param onlyPersonal bool Whether the address may only be set personally.
*/
function setAttributeTypeOnlyPersonal(uint256 ID, bool onlyPersonal) external {
// if the attribute type ID does not exist, there is nothing to remove
require(
isAttributeType(ID),
"unable to set to only personal, no attribute type with the provided ID"
);
// modify the attribute type in the mapping
_attributeTypes[ID].onlyPersonal = onlyPersonal;
}
/**
* @notice Set a secondary source for a given attribute type ID `ID`, with an
* address `registry` of the secondary source in question and a given
* `sourceAttributeTypeID` for attribute type ID to check on the secondary
* source. The secondary source will only be checked for the given attribute in
* cases where no attribute of the given attribute type ID is assigned locally.
* @param ID uint256 The attribute type ID to set the secondary source for.
* @param attributeRegistry address The secondary attribute registry account.
* @param sourceAttributeTypeID uint256 The attribute type ID on the secondary
* source to check.
* @dev To remove a secondary source on an attribute type, the registry address
* should be set to the null address.
*/
function setAttributeTypeSecondarySource(
uint256 ID,
address attributeRegistry,
uint256 sourceAttributeTypeID
) external {
// if the attribute type ID does not exist, there is nothing to remove
require(
isAttributeType(ID),
"unable to set secondary source, no attribute type with the provided ID"
);
// modify the attribute type in the mapping
_attributeTypes[ID].secondarySource = attributeRegistry;
_attributeTypes[ID].secondaryAttributeTypeID = sourceAttributeTypeID;
}
/**
* @notice Set a minimum required stake for a given attribute type ID `ID` and
* an amount of `stake`, to be locked in the jurisdiction upon assignment of
* attributes of the given type. The stake will be applied toward a transaction
* rebate in the event the attribute is revoked, with the remainder returned to
* the staker.
* @param ID uint256 The attribute type ID to set a minimum required stake for.
* @param minimumRequiredStake uint256 The minimum required funds to lock up.
* @dev To remove a stake requirement from an attribute type, the stake amount
* should be set to 0.
*/
function setAttributeTypeMinimumRequiredStake(
uint256 ID,
uint256 minimumRequiredStake
) external {
// if the attribute type ID does not exist, there is nothing to remove
require(
isAttributeType(ID),
"unable to set minimum stake, no attribute type with the provided ID"
);
// modify the attribute type in the mapping
_attributeTypes[ID].minimumStake = minimumRequiredStake;
}
/**
* @notice Set a required fee for a given attribute type ID `ID` and an amount
* of `fee`, to be paid to the owner of the jurisdiction upon assignment of
* attributes of the given type.
* @param ID uint256 The attribute type ID to set the required fee for.
* @param fee uint256 The required fee amount to be paid upon assignment.
* @dev To remove a fee requirement from an attribute type, the fee amount
* should be set to 0.
*/
function setAttributeTypeJurisdictionFee(uint256 ID, uint256 fee) external {
// if the attribute type ID does not exist, there is nothing to remove
require(
isAttributeType(ID),
"unable to set fee, no attribute type with the provided ID"
);
// modify the attribute type in the mapping
_attributeTypes[ID].jurisdictionFee = fee;
}
/**
* @notice Remove the attribute type with ID `ID` from the jurisdiction.
* @param ID uint256 The ID of the attribute type to remove.
* @dev All issued attributes of the given type will become invalid upon
* removal, but will become valid again if the attribute is reinstated.
*/
function removeAttributeType(uint256 ID) external onlyOwner whenNotPaused {
// if the attribute type ID does not exist, there is nothing to remove
require(
isAttributeType(ID),
"unable to remove, no attribute type with the provided ID"
);
// get the attribute ID at the last index of the array
uint256 lastAttributeID = _attributeIDs[_attributeIDs.length.sub(1)];
// set the attributeID at attribute-to-delete.index to the last attribute ID
_attributeIDs[_attributeTypes[ID].index] = lastAttributeID;
// update the index of the attribute type that was moved
_attributeTypes[lastAttributeID].index = _attributeTypes[ID].index;
// remove the (now duplicate) attribute ID at the end by trimming the array
_attributeIDs.length--;
// delete the attribute type's record from the mapping
delete _attributeTypes[ID];
// log the removal of the attribute type
emit AttributeTypeRemoved(ID);
}
/**
* @notice Add account `validator` as a validator with a description
* `description` who can be approved to set attributes of specific types.
* @param validator address The account to assign as the validator.
* @param description string A description of the validator.
* @dev Note that the jurisdiction can add iteslf as a validator if desired.
*/
function addValidator(
address validator,
string description
) external onlyOwner whenNotPaused {
// check that an empty address was not provided by mistake
require(validator != address(0), "must supply a valid address");
// prevent existing validators from being overwritten
require(
!isValidator(validator),
"a validator with the provided address already exists"
);
// prevent duplicate signing keys from being created
require(
_signingKeys[validator] == address(0),
"a signing key matching the provided address already exists"
);
// create a record for the validator
_validators[validator] = Validator({
exists: true,
index: _validatorAccounts.length,
signingKey: validator, // NOTE: this will be initially set to same address
description: description
});
// set the initial signing key (the validator's address) resolving to itself
_signingKeys[validator] = validator;
// add the validator to the end of the _validatorAccounts array
_validatorAccounts.push(validator);
// log the addition of the new validator
emit ValidatorAdded(validator, description);
}
/**
* @notice Remove the validator at address `validator` from the jurisdiction.
* @param validator address The account of the validator to remove.
* @dev Any attributes issued by the validator will become invalid upon their
* removal. If the validator is reinstated, those attributes will become valid
* again. Any approvals to issue attributes of a given type will need to be
* set from scratch in the event a validator is reinstated.
*/
function removeValidator(address validator) external onlyOwner whenNotPaused {
// check that a validator exists at the provided address
require(
isValidator(validator),
"unable to remove, no validator located at the provided address"
);
// first, start removing validator approvals until gas is exhausted
while (_validatorApprovals[validator].length > 0 && gasleft() > 25000) {
// locate the index of last attribute ID in the validator approval group
uint256 lastIndex = _validatorApprovals[validator].length.sub(1);
// locate the validator approval to be removed
uint256 targetApproval = _validatorApprovals[validator][lastIndex];
// remove the record of the approval from the associated attribute type
delete _attributeTypes[targetApproval].approvedValidators[validator];
// remove the record of the index of the approval
delete _validatorApprovalsIndex[validator][targetApproval];
// drop the last attribute ID from the validator approval group
_validatorApprovals[validator].length--;
}
// require that all approvals were successfully removed
require(
_validatorApprovals[validator].length == 0,
"Cannot remove validator - first remove any existing validator approvals"
);
// get the validator address at the last index of the array
address lastAccount = _validatorAccounts[_validatorAccounts.length.sub(1)];
// set the address at validator-to-delete.index to last validator address
_validatorAccounts[_validators[validator].index] = lastAccount;
// update the index of the attribute type that was moved
_validators[lastAccount].index = _validators[validator].index;
// remove (duplicate) validator address at the end by trimming the array
_validatorAccounts.length--;
// remove the validator's signing key from its mapping
delete _signingKeys[_validators[validator].signingKey];
// remove the validator record
delete _validators[validator];
// log the removal of the validator
emit ValidatorRemoved(validator);
}
/**
* @notice Approve the validator at address `validator` to issue attributes of
* the type with ID `attributeTypeID`.
* @param validator address The account of the validator to approve.
* @param attributeTypeID uint256 The ID of the approved attribute type.
*/
function addValidatorApproval(
address validator,
uint256 attributeTypeID
) external onlyOwner whenNotPaused {
// check that the attribute is predefined and that the validator exists
require(
isValidator(validator) && isAttributeType(attributeTypeID),
"must specify both a valid attribute and an available validator"
);
// check that the validator is not already approved
require(
!_attributeTypes[attributeTypeID].approvedValidators[validator],
"validator is already approved on the provided attribute"
);
// set the validator approval status on the attribute
_attributeTypes[attributeTypeID].approvedValidators[validator] = true;
// add the record of the index of the validator approval to be added
uint256 index = _validatorApprovals[validator].length;
_validatorApprovalsIndex[validator][attributeTypeID] = index;
// include the attribute type in the validator approval mapping
_validatorApprovals[validator].push(attributeTypeID);
// log the addition of the validator's attribute type approval
emit ValidatorApprovalAdded(validator, attributeTypeID);
}
/**
* @notice Deny the validator at address `validator` the ability to continue to
* issue attributes of the type with ID `attributeTypeID`.
* @param validator address The account of the validator with removed approval.
* @param attributeTypeID uint256 The ID of the attribute type to unapprove.
* @dev Any attributes of the specified type issued by the validator in
* question will become invalid once the approval is removed. If the approval
* is reinstated, those attributes will become valid again. The approval will
* also be removed if the approved validator is removed.
*/
function removeValidatorApproval(
address validator,
uint256 attributeTypeID
) external onlyOwner whenNotPaused {
// check that the attribute is predefined and that the validator exists
require(
canValidate(validator, attributeTypeID),
"unable to remove validator approval, attribute is already unapproved"
);
// remove the validator approval status from the attribute
delete _attributeTypes[attributeTypeID].approvedValidators[validator];
// locate the index of the last validator approval
uint256 lastIndex = _validatorApprovals[validator].length.sub(1);
// locate the last attribute ID in the validator approval group
uint256 lastAttributeID = _validatorApprovals[validator][lastIndex];
// locate the index of the validator approval to be removed
uint256 index = _validatorApprovalsIndex[validator][attributeTypeID];
// replace the validator approval with the last approval in the array
_validatorApprovals[validator][index] = lastAttributeID;
// drop the last attribute ID from the validator approval group
_validatorApprovals[validator].length--;
// update the record of the index of the swapped-in approval
_validatorApprovalsIndex[validator][lastAttributeID] = index;
// remove the record of the index of the removed approval
delete _validatorApprovalsIndex[validator][attributeTypeID];
// log the removal of the validator's attribute type approval
emit ValidatorApprovalRemoved(validator, attributeTypeID);
}
/**
* @notice Set the public address associated with a validator signing key, used
* to sign off-chain attribute approvals, as `newSigningKey`.
* @param newSigningKey address The address associated with signing key to set.
* @dev Consider having the validator submit a signed proof demonstrating that
* the provided signing key is indeed a signing key in their control - this
* helps mitigate the fringe attack vector where a validator could set the
* address of another validator candidate (especially in the case of a deployed
* smart contract) as their "signing key" in order to block them from being
* added to the jurisdiction (due to the required property of signing keys
* being unique, coupled with the fact that new validators are set up with
* their address as the default initial signing key).
*/
function setValidatorSigningKey(address newSigningKey) external {
require(
isValidator(msg.sender),
"only validators may modify validator signing keys");
// prevent duplicate signing keys from being created
require(
_signingKeys[newSigningKey] == address(0),
"a signing key matching the provided address already exists"
);
// remove validator address as the resolved value for the old key
delete _signingKeys[_validators[msg.sender].signingKey];
// set the signing key to the new value
_validators[msg.sender].signingKey = newSigningKey;
// add validator address as the resolved value for the new key
_signingKeys[newSigningKey] = msg.sender;
// log the modification of the signing key
emit ValidatorSigningKeyModified(msg.sender, newSigningKey);
}
/**
* @notice Issue an attribute of the type with ID `attributeTypeID` and a value
* of `value` to `account` if `message.caller.address()` is approved validator.
* @param account address The account to issue the attribute on.
* @param attributeTypeID uint256 The ID of the attribute type to issue.
* @param value uint256 An optional value for the issued attribute.
* @dev Existing attributes of the given type on the address must be removed
* in order to set a new attribute. Be aware that ownership of the account to
* which the attribute is assigned may still be transferable - restricting
* assignment to externally-owned accounts may partially alleviate this issue.
*/
function issueAttribute(
address account,
uint256 attributeTypeID,
uint256 value
) external payable whenNotPaused {
require(
canValidate(msg.sender, attributeTypeID),
"only approved validators may assign attributes of this type"
);
require(
!_issuedAttributes[account][attributeTypeID].exists,
"duplicate attributes are not supported, remove existing attribute first"
);
// retrieve required minimum stake and jurisdiction fees on attribute type
uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake;
uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee;
uint256 stake = msg.value.sub(jurisdictionFee);
require(
stake >= minimumStake,
"attribute requires a greater value than is currently provided"
);
// store attribute value and amount of ether staked in correct scope
_issuedAttributes[account][attributeTypeID] = IssuedAttribute({
exists: true,
setPersonally: false,
operator: address(0),
validator: msg.sender,
value: value,
stake: stake
});
// log the addition of the attribute
emit AttributeAdded(msg.sender, account, attributeTypeID, value);
// log allocation of staked funds to the attribute if applicable
if (stake > 0) {
emit StakeAllocated(msg.sender, attributeTypeID, stake);
}
// pay jurisdiction fee to the owner of the jurisdiction if applicable
if (jurisdictionFee > 0) {
// NOTE: send is chosen over transfer to prevent cases where a improperly
// configured fallback function could block addition of an attribute
if (owner().send(jurisdictionFee)) {
emit FeePaid(owner(), msg.sender, attributeTypeID, jurisdictionFee);
} else {
_recoverableFunds = _recoverableFunds.add(jurisdictionFee);
}
}
}
/**
* @notice Revoke the attribute of the type with ID `attributeTypeID` from
* `account` if `message.caller.address()` is the issuing validator.
* @param account address The account to issue the attribute on.
* @param attributeTypeID uint256 The ID of the attribute type to issue.
* @dev Validators may still revoke issued attributes even after they have been
* removed or had their approval to issue the attribute type removed - this
* enables them to address any objectionable issuances before being reinstated.
*/
function revokeAttribute(
address account,
uint256 attributeTypeID
) external whenNotPaused {
// ensure that an attribute with the given account and attribute exists
require(
_issuedAttributes[account][attributeTypeID].exists,
"only existing attributes may be removed"
);
// determine the assigned validator on the user attribute
address validator = _issuedAttributes[account][attributeTypeID].validator;
// caller must be either the jurisdiction owner or the assigning validator
require(
msg.sender == validator || msg.sender == owner(),
"only jurisdiction or issuing validators may revoke arbitrary attributes"
);
// determine if attribute has any stake in order to refund transaction fee
uint256 stake = _issuedAttributes[account][attributeTypeID].stake;
// determine the correct address to refund the staked amount to
address refundAddress;
if (_issuedAttributes[account][attributeTypeID].setPersonally) {
refundAddress = account;
} else {
address operator = _issuedAttributes[account][attributeTypeID].operator;
if (operator == address(0)) {
refundAddress = validator;
} else {
refundAddress = operator;
}
}
// remove the attribute from the designated user account
delete _issuedAttributes[account][attributeTypeID];
// log the removal of the attribute
emit AttributeRemoved(validator, account, attributeTypeID);
// pay out any refunds and return the excess stake to the user
if (stake > 0 && address(this).balance >= stake) {
// NOTE: send is chosen over transfer to prevent cases where a malicious
// fallback function could forcibly block an attribute's removal. Another
// option is to allow a user to pull the staked amount after the removal.
// NOTE: refine transaction rebate gas calculation! Setting this value too
// high gives validators the incentive to revoke valid attributes. Simply
// checking against gasLeft() & adding the final gas usage won't give the
// correct transaction cost, as freeing space refunds gas upon completion.
uint256 transactionGas = 37700; // <--- WARNING: THIS IS APPROXIMATE
uint256 transactionCost = transactionGas.mul(tx.gasprice);
// if stake exceeds allocated transaction cost, refund user the difference
if (stake > transactionCost) {
// refund the excess stake to the address that contributed the funds
if (refundAddress.send(stake.sub(transactionCost))) {
emit StakeRefunded(
refundAddress,
attributeTypeID,
stake.sub(transactionCost)
);
} else {
_recoverableFunds = _recoverableFunds.add(stake.sub(transactionCost));
}
// emit an event for the payment of the transaction rebate
emit TransactionRebatePaid(
tx.origin,
refundAddress,
attributeTypeID,
transactionCost
);
// refund the cost of the transaction to the trasaction submitter
tx.origin.transfer(transactionCost);
// otherwise, allocate entire stake to partially refunding the transaction
} else {
// emit an event for the payment of the partial transaction rebate
emit TransactionRebatePaid(
tx.origin,
refundAddress,
attributeTypeID,
stake
);
// refund the partial cost of the transaction to trasaction submitter
tx.origin.transfer(stake);
}
}
}
/**
* @notice Add an attribute of the type with ID `attributeTypeID`, an attribute
* value of `value`, and an associated validator fee of `validatorFee` to
* account of `msg.sender` by passing in a signed attribute approval with
* signature `signature`.
* @param attributeTypeID uint256 The ID of the attribute type to add.
* @param value uint256 The value for the attribute to add.
* @param validatorFee uint256 The fee to be paid to the issuing validator.
* @param signature bytes The signature from the validator attribute approval.
*/
function addAttribute(
uint256 attributeTypeID,
uint256 value,
uint256 validatorFee,
bytes signature
) external payable {
// NOTE: determine best course of action when the attribute already exists
// NOTE: consider utilizing bytes32 type for attributes and values
// NOTE: does not currently support an extraData parameter, consider adding
// NOTE: if msg.sender is a proxy contract, its ownership may be transferred
// at will, circumventing any token transfer restrictions. Restricting usage
// to only externally owned accounts may partially alleviate this concern.
// NOTE: cosider including a salt (or better, nonce) parameter so that when
// a user adds an attribute, then it gets revoked, the user can get a new
// signature from the validator and renew the attribute using that. The main
// downside is that everyone will have to keep track of the extra parameter.
// Another solution is to just modifiy the required stake or fee amount.
require(
!_issuedAttributes[msg.sender][attributeTypeID].exists,
"duplicate attributes are not supported, remove existing attribute first"
);
// retrieve required minimum stake and jurisdiction fees on attribute type
uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake;
uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee;
uint256 stake = msg.value.sub(validatorFee).sub(jurisdictionFee);
require(
stake >= minimumStake,
"attribute requires a greater value than is currently provided"
);
// signed data hash constructed according to EIP-191-0x45 to prevent replays
bytes32 hash = keccak256(
abi.encodePacked(
address(this),
msg.sender,
address(0),
msg.value,
validatorFee,
attributeTypeID,
value
)
);
require(
!_invalidAttributeApprovalHashes[hash],
"signed attribute approvals from validators may not be reused"
);
// extract the key used to sign the message hash
address signingKey = hash.toEthSignedMessageHash().recover(signature);
// retrieve the validator who controls the extracted key
address validator = _signingKeys[signingKey];
require(
canValidate(validator, attributeTypeID),
"signature does not match an approved validator for given attribute type"
);
// store attribute value and amount of ether staked in correct scope
_issuedAttributes[msg.sender][attributeTypeID] = IssuedAttribute({
exists: true,
setPersonally: true,
operator: address(0),
validator: validator,
value: value,
stake: stake
// NOTE: no extraData included
});
// flag the signed approval as invalid once it's been used to set attribute
_invalidAttributeApprovalHashes[hash] = true;
// log the addition of the attribute
emit AttributeAdded(validator, msg.sender, attributeTypeID, value);
// log allocation of staked funds to the attribute if applicable
if (stake > 0) {
emit StakeAllocated(msg.sender, attributeTypeID, stake);
}
// pay jurisdiction fee to the owner of the jurisdiction if applicable
if (jurisdictionFee > 0) {
// NOTE: send is chosen over transfer to prevent cases where a improperly
// configured fallback function could block addition of an attribute
if (owner().send(jurisdictionFee)) {
emit FeePaid(owner(), msg.sender, attributeTypeID, jurisdictionFee);
} else {
_recoverableFunds = _recoverableFunds.add(jurisdictionFee);
}
}
// pay validator fee to the issuing validator's address if applicable
if (validatorFee > 0) {
// NOTE: send is chosen over transfer to prevent cases where a improperly
// configured fallback function could block addition of an attribute
if (validator.send(validatorFee)) {
emit FeePaid(validator, msg.sender, attributeTypeID, validatorFee);
} else {
_recoverableFunds = _recoverableFunds.add(validatorFee);
}
}
}
/**
* @notice Remove an attribute of the type with ID `attributeTypeID` from
* account of `msg.sender`.
* @param attributeTypeID uint256 The ID of the attribute type to remove.
*/
function removeAttribute(uint256 attributeTypeID) external {
// attributes may only be removed by the user if they are not restricted
require(
!_attributeTypes[attributeTypeID].restricted,
"only jurisdiction or issuing validator may remove a restricted attribute"
);
require(
_issuedAttributes[msg.sender][attributeTypeID].exists,
"only existing attributes may be removed"
);
// determine the assigned validator on the user attribute
address validator = _issuedAttributes[msg.sender][attributeTypeID].validator;
// determine if the attribute has a staked value
uint256 stake = _issuedAttributes[msg.sender][attributeTypeID].stake;
// determine the correct address to refund the staked amount to
address refundAddress;
if (_issuedAttributes[msg.sender][attributeTypeID].setPersonally) {
refundAddress = msg.sender;
} else {
address operator = _issuedAttributes[msg.sender][attributeTypeID].operator;
if (operator == address(0)) {
refundAddress = validator;
} else {
refundAddress = operator;
}
}
// remove the attribute from the user address
delete _issuedAttributes[msg.sender][attributeTypeID];
// log the removal of the attribute
emit AttributeRemoved(validator, msg.sender, attributeTypeID);
// if the attribute has any staked balance, refund it to the user
if (stake > 0 && address(this).balance >= stake) {
// NOTE: send is chosen over transfer to prevent cases where a malicious
// fallback function could forcibly block an attribute's removal
if (refundAddress.send(stake)) {
emit StakeRefunded(refundAddress, attributeTypeID, stake);
} else {
_recoverableFunds = _recoverableFunds.add(stake);
}
}
}
/**
* @notice Add an attribute of the type with ID `attributeTypeID`, an attribute
* value of `value`, and an associated validator fee of `validatorFee` to
* account `account` by passing in a signed attribute approval with signature
* `signature`.
* @param account address The account to add the attribute to.
* @param attributeTypeID uint256 The ID of the attribute type to add.
* @param value uint256 The value for the attribute to add.
* @param validatorFee uint256 The fee to be paid to the issuing validator.
* @param signature bytes The signature from the validator attribute approval.
* @dev Restricted attribute types can only be removed by issuing validators or
* the jurisdiction itself.
*/
function addAttributeFor(
address account,
uint256 attributeTypeID,
uint256 value,
uint256 validatorFee,
bytes signature
) external payable {
// NOTE: determine best course of action when the attribute already exists
// NOTE: consider utilizing bytes32 type for attributes and values
// NOTE: does not currently support an extraData parameter, consider adding
// NOTE: if msg.sender is a proxy contract, its ownership may be transferred
// at will, circumventing any token transfer restrictions. Restricting usage
// to only externally owned accounts may partially alleviate this concern.
// NOTE: consider including a salt (or better, nonce) parameter so that when
// a user adds an attribute, then it gets revoked, the user can get a new
// signature from the validator and renew the attribute using that. The main
// downside is that everyone will have to keep track of the extra parameter.
// Another solution is to just modifiy the required stake or fee amount.
// attributes may only be added by a third party if onlyPersonal is false
require(
!_attributeTypes[attributeTypeID].onlyPersonal,
"only operatable attributes may be added on behalf of another address"
);
require(
!_issuedAttributes[account][attributeTypeID].exists,
"duplicate attributes are not supported, remove existing attribute first"
);
// retrieve required minimum stake and jurisdiction fees on attribute type
uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake;
uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee;
uint256 stake = msg.value.sub(validatorFee).sub(jurisdictionFee);
require(
stake >= minimumStake,
"attribute requires a greater value than is currently provided"
);
// signed data hash constructed according to EIP-191-0x45 to prevent replays
bytes32 hash = keccak256(
abi.encodePacked(
address(this),
account,
msg.sender,
msg.value,
validatorFee,
attributeTypeID,
value
)
);
require(
!_invalidAttributeApprovalHashes[hash],
"signed attribute approvals from validators may not be reused"
);
// extract the key used to sign the message hash
address signingKey = hash.toEthSignedMessageHash().recover(signature);
// retrieve the validator who controls the extracted key
address validator = _signingKeys[signingKey];
require(
canValidate(validator, attributeTypeID),
"signature does not match an approved validator for provided attribute"
);
// store attribute value and amount of ether staked in correct scope
_issuedAttributes[account][attributeTypeID] = IssuedAttribute({
exists: true,
setPersonally: false,
operator: msg.sender,
validator: validator,
value: value,
stake: stake
// NOTE: no extraData included
});
// flag the signed approval as invalid once it's been used to set attribute
_invalidAttributeApprovalHashes[hash] = true;
// log the addition of the attribute
emit AttributeAdded(validator, account, attributeTypeID, value);
// log allocation of staked funds to the attribute if applicable
// NOTE: the staker is the entity that pays the fee here!
if (stake > 0) {
emit StakeAllocated(msg.sender, attributeTypeID, stake);
}
// pay jurisdiction fee to the owner of the jurisdiction if applicable
if (jurisdictionFee > 0) {
// NOTE: send is chosen over transfer to prevent cases where a improperly
// configured fallback function could block addition of an attribute
if (owner().send(jurisdictionFee)) {
emit FeePaid(owner(), msg.sender, attributeTypeID, jurisdictionFee);
} else {
_recoverableFunds = _recoverableFunds.add(jurisdictionFee);
}
}
// pay validator fee to the issuing validator's address if applicable
if (validatorFee > 0) {
// NOTE: send is chosen over transfer to prevent cases where a improperly
// configured fallback function could block addition of an attribute
if (validator.send(validatorFee)) {
emit FeePaid(validator, msg.sender, attributeTypeID, validatorFee);
} else {
_recoverableFunds = _recoverableFunds.add(validatorFee);
}
}
}
/**
* @notice Remove an attribute of the type with ID `attributeTypeID` from
* account of `account`.
* @param account address The account to remove the attribute from.
* @param attributeTypeID uint256 The ID of the attribute type to remove.
* @dev Restricted attribute types can only be removed by issuing validators or
* the jurisdiction itself.
*/
function removeAttributeFor(address account, uint256 attributeTypeID) external {
// attributes may only be removed by the user if they are not restricted
require(
!_attributeTypes[attributeTypeID].restricted,
"only jurisdiction or issuing validator may remove a restricted attribute"
);
require(
_issuedAttributes[account][attributeTypeID].exists,
"only existing attributes may be removed"
);
require(
_issuedAttributes[account][attributeTypeID].operator == msg.sender,
"only an assigning operator may remove attribute on behalf of an address"
);
// determine the assigned validator on the user attribute
address validator = _issuedAttributes[account][attributeTypeID].validator;
// determine if the attribute has a staked value
uint256 stake = _issuedAttributes[account][attributeTypeID].stake;
// remove the attribute from the user address
delete _issuedAttributes[account][attributeTypeID];
// log the removal of the attribute
emit AttributeRemoved(validator, account, attributeTypeID);
// if the attribute has any staked balance, refund it to the user
if (stake > 0 && address(this).balance >= stake) {
// NOTE: send is chosen over transfer to prevent cases where a malicious
// fallback function could forcibly block an attribute's removal
if (msg.sender.send(stake)) {
emit StakeRefunded(msg.sender, attributeTypeID, stake);
} else {
_recoverableFunds = _recoverableFunds.add(stake);
}
}
}
/**
* @notice Invalidate a signed attribute approval before it has been set by
* supplying the hash of the approval `hash` and the signature `signature`.
* @param hash bytes32 The hash of the attribute approval.
* @param signature bytes The hash's signature, resolving to the signing key.
* @dev Attribute approvals can only be removed by issuing validators or the
* jurisdiction itself.
*/
function invalidateAttributeApproval(
bytes32 hash,
bytes signature
) external {
// determine the assigned validator on the signed attribute approval
address validator = _signingKeys[
hash.toEthSignedMessageHash().recover(signature) // signingKey
];
// caller must be either the jurisdiction owner or the assigning validator
require(
msg.sender == validator || msg.sender == owner(),
"only jurisdiction or issuing validator may invalidate attribute approval"
);
// add the hash to the set of invalid attribute approval hashes
_invalidAttributeApprovalHashes[hash] = true;
}
/**
* @notice Check if an attribute of the type with ID `attributeTypeID` has
* been assigned to the account at `account` and is currently valid.
* @param account address The account to check for a valid attribute.
* @param attributeTypeID uint256 The ID of the attribute type to check for.
* @return True if the attribute is assigned and valid, false otherwise.
* @dev This function MUST return either true or false - i.e. calling this
* function MUST NOT cause the caller to revert.
*/
function hasAttribute(
address account,
uint256 attributeTypeID
) external view returns (bool) {
address validator = _issuedAttributes[account][attributeTypeID].validator;
return (
(
_validators[validator].exists && // isValidator(validator)
_attributeTypes[attributeTypeID].approvedValidators[validator] &&
_attributeTypes[attributeTypeID].exists //isAttributeType(attributeTypeID)
) || (
_attributeTypes[attributeTypeID].secondarySource != address(0) &&
secondaryHasAttribute(
_attributeTypes[attributeTypeID].secondarySource,
account,
_attributeTypes[attributeTypeID].secondaryAttributeTypeID
)
)
);
}
/**
* @notice Retrieve the value of the attribute of the type with ID
* `attributeTypeID` on the account at `account`, assuming it is valid.
* @param account address The account to check for the given attribute value.
* @param attributeTypeID uint256 The ID of the attribute type to check for.
* @return The attribute value if the attribute is valid, reverts otherwise.
* @dev This function MUST revert if a directly preceding or subsequent
* function call to `hasAttribute` with identical `account` and
* `attributeTypeID` parameters would return false.
*/
function getAttributeValue(
address account,
uint256 attributeTypeID
) external view returns (uint256 value) {
// gas optimization: get validator & call canValidate function body directly
address validator = _issuedAttributes[account][attributeTypeID].validator;
if (
_validators[validator].exists && // isValidator(validator)
_attributeTypes[attributeTypeID].approvedValidators[validator] &&
_attributeTypes[attributeTypeID].exists //isAttributeType(attributeTypeID)
) {
return _issuedAttributes[account][attributeTypeID].value;
} else if (
_attributeTypes[attributeTypeID].secondarySource != address(0)
) {
// if attributeTypeID = uint256 of 'wyre-yes-token', use special handling
if (_attributeTypes[attributeTypeID].secondaryAttributeTypeID == 2423228754106148037712574142965102) {
require(
IERC20(
_attributeTypes[attributeTypeID].secondarySource
).balanceOf(account) >= 1,
"no Yes Token has been issued to the provided account"
);
return 1; // this could also return a specific yes token's country code?
}
// first ensure hasAttribute on the secondary source returns true
require(
AttributeRegistryInterface(
_attributeTypes[attributeTypeID].secondarySource
).hasAttribute(
account, _attributeTypes[attributeTypeID].secondaryAttributeTypeID
),
"attribute of the provided type is not assigned to the provided account"
);
return (
AttributeRegistryInterface(
_attributeTypes[attributeTypeID].secondarySource
).getAttributeValue(
account, _attributeTypes[attributeTypeID].secondaryAttributeTypeID
)
);
}
// NOTE: checking for values of invalid attributes will revert
revert("could not find an attribute value at the provided account and ID");
}
/**
* @notice Determine if a validator at account `validator` is able to issue
* attributes of the type with ID `attributeTypeID`.
* @param validator address The account of the validator.
* @param attributeTypeID uint256 The ID of the attribute type to check.
* @return True if the validator can issue attributes of the given type, false
* otherwise.
*/
function canIssueAttributeType(
address validator,
uint256 attributeTypeID
) external view returns (bool) {
return canValidate(validator, attributeTypeID);
}
/**
* @notice Get a description of the attribute type with ID `attributeTypeID`.
* @param attributeTypeID uint256 The ID of the attribute type to check for.
* @return A description of the attribute type.
*/
function getAttributeTypeDescription(
uint256 attributeTypeID
) external view returns (
string description
) {
return _attributeTypes[attributeTypeID].description;
}
/**
* @notice Get comprehensive information on an attribute type with ID
* `attributeTypeID`.
* @param attributeTypeID uint256 The attribute type ID in question.
* @return Information on the attribute type in question.
*/
function getAttributeTypeInformation(
uint256 attributeTypeID
) external view returns (
string description,
bool isRestricted,
bool isOnlyPersonal,
address secondarySource,
uint256 secondaryAttributeTypeID,
uint256 minimumRequiredStake,
uint256 jurisdictionFee
) {
return (
_attributeTypes[attributeTypeID].description,
_attributeTypes[attributeTypeID].restricted,
_attributeTypes[attributeTypeID].onlyPersonal,
_attributeTypes[attributeTypeID].secondarySource,
_attributeTypes[attributeTypeID].secondaryAttributeTypeID,
_attributeTypes[attributeTypeID].minimumStake,
_attributeTypes[attributeTypeID].jurisdictionFee
);
}
/**
* @notice Get a description of the validator at account `validator`.
* @param validator address The account of the validator in question.
* @return A description of the validator.
*/
function getValidatorDescription(
address validator
) external view returns (
string description
) {
return _validators[validator].description;
}
/**
* @notice Get the signing key of the validator at account `validator`.
* @param validator address The account of the validator in question.
* @return The signing key of the validator.
*/
function getValidatorSigningKey(
address validator
) external view returns (
address signingKey
) {
return _validators[validator].signingKey;
}
/**
* @notice Find the validator that issued the attribute of the type with ID
* `attributeTypeID` on the account at `account` and determine if the
* validator is still valid.
* @param account address The account that contains the attribute be checked.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @return The validator and the current status of the validator as it
* pertains to the attribute type in question.
* @dev if no attribute of the given attribute type exists on the account, the
* function will return (address(0), false).
*/
function getAttributeValidator(
address account,
uint256 attributeTypeID
) external view returns (
address validator,
bool isStillValid
) {
address issuer = _issuedAttributes[account][attributeTypeID].validator;
return (issuer, canValidate(issuer, attributeTypeID));
}
/**
* @notice Count the number of attribute types defined by the registry.
* @return The number of available attribute types.
* @dev This function MUST return a positive integer value - i.e. calling
* this function MUST NOT cause the caller to revert.
*/
function countAttributeTypes() external view returns (uint256) {
return _attributeIDs.length;
}
/**
* @notice Get the ID of the attribute type at index `index`.
* @param index uint256 The index of the attribute type in question.
* @return The ID of the attribute type.
* @dev This function MUST revert if the provided `index` value falls outside
* of the range of the value returned from a directly preceding or subsequent
* function call to `countAttributeTypes`. It MUST NOT revert if the provided
* `index` value falls inside said range.
*/
function getAttributeTypeID(uint256 index) external view returns (uint256) {
require(
index < _attributeIDs.length,
"provided index is outside of the range of defined attribute type IDs"
);
return _attributeIDs[index];
}
/**
* @notice Get the IDs of all available attribute types on the jurisdiction.
* @return A dynamic array containing all available attribute type IDs.
*/
function getAttributeTypeIDs() external view returns (uint256[]) {
return _attributeIDs;
}
/**
* @notice Count the number of validators defined by the jurisdiction.
* @return The number of defined validators.
*/
function countValidators() external view returns (uint256) {
return _validatorAccounts.length;
}
/**
* @notice Get the account of the validator at index `index`.
* @param index uint256 The index of the validator in question.
* @return The account of the validator.
*/
function getValidator(
uint256 index
) external view returns (address) {
return _validatorAccounts[index];
}
/**
* @notice Get the accounts of all available validators on the jurisdiction.
* @return A dynamic array containing all available validator accounts.
*/
function getValidators() external view returns (address[]) {
return _validatorAccounts;
}
/**
* @notice Determine if the interface ID `interfaceID` is supported (ERC-165)
* @param interfaceID bytes4 The interface ID in question.
* @return True if the interface is supported, false otherwise.
* @dev this function will produce a compiler warning recommending that the
* visibility be set to pure, but the interface expects a view function.
* Supported interfaces include ERC-165 (0x01ffc9a7) and the attribute
* registry interface (0x5f46473f).
*/
function supportsInterface(bytes4 interfaceID) external view returns (bool) {
return (
interfaceID == this.supportsInterface.selector || // ERC165
interfaceID == (
this.hasAttribute.selector
^ this.getAttributeValue.selector
^ this.countAttributeTypes.selector
^ this.getAttributeTypeID.selector
) // AttributeRegistryInterface
); // 0x01ffc9a7 || 0x5f46473f
}
/**
* @notice Get the hash of a given attribute approval.
* @param account address The account specified by the attribute approval.
* @param operator address An optional account permitted to submit approval.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @param value uint256 The value of the attribute in the approval.
* @param fundsRequired uint256 The amount to be included with the approval.
* @param validatorFee uint256 The required fee to be paid to the validator.
* @return The hash of the attribute approval.
*/
function getAttributeApprovalHash(
address account,
address operator,
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee
) external view returns (
bytes32 hash
) {
return calculateAttributeApprovalHash(
account,
operator,
attributeTypeID,
value,
fundsRequired,
validatorFee
);
}
/**
* @notice Check if a given signed attribute approval is currently valid when
* submitted directly by `msg.sender`.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @param value uint256 The value of the attribute in the approval.
* @param fundsRequired uint256 The amount to be included with the approval.
* @param validatorFee uint256 The required fee to be paid to the validator.
* @param signature bytes The attribute approval signature, based on a hash of
* the other parameters and the submitting account.
* @return True if the approval is currently valid, false otherwise.
*/
function canAddAttribute(
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee,
bytes signature
) external view returns (bool) {
// signed data hash constructed according to EIP-191-0x45 to prevent replays
bytes32 hash = calculateAttributeApprovalHash(
msg.sender,
address(0),
attributeTypeID,
value,
fundsRequired,
validatorFee
);
// recover the address associated with the signature of the message hash
address signingKey = hash.toEthSignedMessageHash().recover(signature);
// retrieve variables necessary to perform checks
address validator = _signingKeys[signingKey];
uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake;
uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee;
// determine if the attribute can currently be added.
// NOTE: consider returning an error code along with the boolean.
return (
fundsRequired >= minimumStake.add(jurisdictionFee).add(validatorFee) &&
!_invalidAttributeApprovalHashes[hash] &&
canValidate(validator, attributeTypeID) &&
!_issuedAttributes[msg.sender][attributeTypeID].exists
);
}
/**
* @notice Check if a given signed attribute approval is currently valid for a
* given account when submitted by the operator at `msg.sender`.
* @param account address The account specified by the attribute approval.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @param value uint256 The value of the attribute in the approval.
* @param fundsRequired uint256 The amount to be included with the approval.
* @param validatorFee uint256 The required fee to be paid to the validator.
* @param signature bytes The attribute approval signature, based on a hash of
* the other parameters and the submitting account.
* @return True if the approval is currently valid, false otherwise.
*/
function canAddAttributeFor(
address account,
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee,
bytes signature
) external view returns (bool) {
// signed data hash constructed according to EIP-191-0x45 to prevent replays
bytes32 hash = calculateAttributeApprovalHash(
account,
msg.sender,
attributeTypeID,
value,
fundsRequired,
validatorFee
);
// recover the address associated with the signature of the message hash
address signingKey = hash.toEthSignedMessageHash().recover(signature);
// retrieve variables necessary to perform checks
address validator = _signingKeys[signingKey];
uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake;
uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee;
// determine if the attribute can currently be added.
// NOTE: consider returning an error code along with the boolean.
return (
fundsRequired >= minimumStake.add(jurisdictionFee).add(validatorFee) &&
!_invalidAttributeApprovalHashes[hash] &&
canValidate(validator, attributeTypeID) &&
!_issuedAttributes[account][attributeTypeID].exists
);
}
/**
* @notice Determine if an attribute type with ID `attributeTypeID` is
* currently defined on the jurisdiction.
* @param attributeTypeID uint256 The attribute type ID in question.
* @return True if the attribute type is defined, false otherwise.
*/
function isAttributeType(uint256 attributeTypeID) public view returns (bool) {
return _attributeTypes[attributeTypeID].exists;
}
/**
* @notice Determine if the account `account` is currently assigned as a
* validator on the jurisdiction.
* @param account address The account to check for validator status.
* @return True if the account is assigned as a validator, false otherwise.
*/
function isValidator(address account) public view returns (bool) {
return _validators[account].exists;
}
/**
* @notice Check for recoverable funds that have become locked in the
* jurisdiction as a result of improperly configured receivers for payments of
* fees or remaining stake. Note that funds sent into the jurisdiction as a
* result of coinbase assignment or as the recipient of a selfdestruct will
* not be recoverable.
* @return The total tracked recoverable funds.
*/
function recoverableFunds() public view returns (uint256) {
// return the total tracked recoverable funds.
return _recoverableFunds;
}
/**
* @notice Check for recoverable tokens that are owned by the jurisdiction at
* the token contract address of `token`.
* @param token address The account where token contract is located.
* @return The total recoverable tokens.
*/
function recoverableTokens(address token) public view returns (uint256) {
// return the total tracked recoverable tokens.
return IERC20(token).balanceOf(address(this));
}
/**
* @notice Recover funds that have become locked in the jurisdiction as a
* result of improperly configured receivers for payments of fees or remaining
* stake by transferring an amount of `value` to the address at `account`.
* Note that funds sent into the jurisdiction as a result of coinbase
* assignment or as the recipient of a selfdestruct will not be recoverable.
* @param account address The account to send recovered tokens.
* @param value uint256 The amount of tokens to be sent.
*/
function recoverFunds(address account, uint256 value) public onlyOwner {
// safely deduct the value from the total tracked recoverable funds.
_recoverableFunds = _recoverableFunds.sub(value);
// transfer the value to the specified account & revert if any error occurs.
account.transfer(value);
}
/**
* @notice Recover tokens that are owned by the jurisdiction at the token
* contract address of `token`, transferring an amount of `value` to the
* address at `account`.
* @param token address The account where token contract is located.
* @param account address The account to send recovered funds.
* @param value uint256 The amount of ether to be sent.
*/
function recoverTokens(
address token,
address account,
uint256 value
) public onlyOwner {
// transfer the value to the specified account & revert if any error occurs.
require(IERC20(token).transfer(account, value));
}
/**
* @notice Internal function to determine if a validator at account
* `validator` can issue attributes of the type with ID `attributeTypeID`.
* @param validator address The account of the validator.
* @param attributeTypeID uint256 The ID of the attribute type to check.
* @return True if the validator can issue attributes of the given type, false
* otherwise.
*/
function canValidate(
address validator,
uint256 attributeTypeID
) internal view returns (bool) {
return (
_validators[validator].exists && // isValidator(validator)
_attributeTypes[attributeTypeID].approvedValidators[validator] &&
_attributeTypes[attributeTypeID].exists // isAttributeType(attributeTypeID)
);
}
// internal helper function for getting the hash of an attribute approval
function calculateAttributeApprovalHash(
address account,
address operator,
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee
) internal view returns (bytes32 hash) {
return keccak256(
abi.encodePacked(
address(this),
account,
operator,
fundsRequired,
validatorFee,
attributeTypeID,
value
)
);
}
// helper function, won't revert calling hasAttribute on secondary registries
function secondaryHasAttribute(
address source,
address account,
uint256 attributeTypeID
) internal view returns (bool result) {
// if attributeTypeID = uint256 of 'wyre-yes-token', use special handling
if (attributeTypeID == 2423228754106148037712574142965102) {
return (IERC20(source).balanceOf(account) >= 1);
}
uint256 maxGas = gasleft() > 20000 ? 20000 : gasleft();
bytes memory encodedParams = abi.encodeWithSelector(
this.hasAttribute.selector,
account,
attributeTypeID
);
assembly {
let encodedParams_data := add(0x20, encodedParams)
let encodedParams_size := mload(encodedParams)
let output := mload(0x40) // get storage start from free memory pointer
mstore(output, 0x0) // set up the location for output of staticcall
let success := staticcall(
maxGas, // maximum of 20k gas can be forwarded
source, // address of attribute registry to call
encodedParams_data, // inputs are stored at pointer location
encodedParams_size, // inputs are 68 bytes (4 + 32 * 2)
output, // return to designated free space
0x20 // output is one word, or 32 bytes
)
switch success // instrumentation bug: use switch instead of if
case 1 { // only recognize successful staticcall output
result := mload(output) // set the output to the return value
}
}
}
} | * @notice Add an attribute of the type with ID `attributeTypeID`, an attribute value of `value`, and an associated validator fee of `validatorFee` to account `account` by passing in a signed attribute approval with signature `signature`. @param account address The account to add the attribute to. @param attributeTypeID uint256 The ID of the attribute type to add. @param value uint256 The value for the attribute to add. @param validatorFee uint256 The fee to be paid to the issuing validator. @param signature bytes The signature from the validator attribute approval. @dev Restricted attribute types can only be removed by issuing validators or the jurisdiction itself./ NOTE: determine best course of action when the attribute already exists NOTE: consider utilizing bytes32 type for attributes and values NOTE: does not currently support an extraData parameter, consider adding NOTE: if msg.sender is a proxy contract, its ownership may be transferred at will, circumventing any token transfer restrictions. Restricting usage to only externally owned accounts may partially alleviate this concern. NOTE: consider including a salt (or better, nonce) parameter so that when a user adds an attribute, then it gets revoked, the user can get a new signature from the validator and renew the attribute using that. The main downside is that everyone will have to keep track of the extra parameter. Another solution is to just modifiy the required stake or fee amount. attributes may only be added by a third party if onlyPersonal is false retrieve required minimum stake and jurisdiction fees on attribute type signed data hash constructed according to EIP-191-0x45 to prevent replays extract the key used to sign the message hash retrieve the validator who controls the extracted key store attribute value and amount of ether staked in correct scope NOTE: no extraData included log allocation of staked funds to the attribute if applicable NOTE: the staker is the entity that pays the fee here! pay jurisdiction fee to the owner of the jurisdiction if applicable NOTE: send is chosen over transfer to prevent cases where a improperly configured fallback function could block addition of an attribute pay validator fee to the issuing validator's address if applicable NOTE: send is chosen over transfer to prevent cases where a improperly configured fallback function could block addition of an attribute | function addAttributeFor(
address account,
uint256 attributeTypeID,
uint256 value,
uint256 validatorFee,
bytes signature
) external payable {
require(
!_attributeTypes[attributeTypeID].onlyPersonal,
"only operatable attributes may be added on behalf of another address"
);
require(
!_issuedAttributes[account][attributeTypeID].exists,
"duplicate attributes are not supported, remove existing attribute first"
);
uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake;
uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee;
uint256 stake = msg.value.sub(validatorFee).sub(jurisdictionFee);
require(
stake >= minimumStake,
"attribute requires a greater value than is currently provided"
);
bytes32 hash = keccak256(
abi.encodePacked(
address(this),
account,
msg.sender,
msg.value,
validatorFee,
attributeTypeID,
value
)
);
require(
!_invalidAttributeApprovalHashes[hash],
"signed attribute approvals from validators may not be reused"
);
address signingKey = hash.toEthSignedMessageHash().recover(signature);
address validator = _signingKeys[signingKey];
require(
canValidate(validator, attributeTypeID),
"signature does not match an approved validator for provided attribute"
);
_issuedAttributes[account][attributeTypeID] = IssuedAttribute({
exists: true,
setPersonally: false,
operator: msg.sender,
validator: validator,
value: value,
stake: stake
});
if (stake > 0) {
emit StakeAllocated(msg.sender, attributeTypeID, stake);
}
if (jurisdictionFee > 0) {
if (owner().send(jurisdictionFee)) {
emit FeePaid(owner(), msg.sender, attributeTypeID, jurisdictionFee);
_recoverableFunds = _recoverableFunds.add(jurisdictionFee);
}
}
if (validatorFee > 0) {
if (validator.send(validatorFee)) {
emit FeePaid(validator, msg.sender, attributeTypeID, validatorFee);
_recoverableFunds = _recoverableFunds.add(validatorFee);
}
}
}
| 1,829,714 | [
1,
986,
392,
1566,
434,
326,
618,
598,
1599,
1375,
4589,
559,
734,
9191,
392,
1566,
460,
434,
1375,
1132,
9191,
471,
392,
3627,
4213,
14036,
434,
1375,
7357,
14667,
68,
358,
2236,
1375,
4631,
68,
635,
9588,
316,
279,
6726,
1566,
23556,
598,
3372,
1375,
8195,
8338,
225,
2236,
1758,
1021,
2236,
358,
527,
326,
1566,
358,
18,
225,
1566,
559,
734,
2254,
5034,
1021,
1599,
434,
326,
1566,
618,
358,
527,
18,
225,
460,
2254,
5034,
1021,
460,
364,
326,
1566,
358,
527,
18,
225,
4213,
14667,
2254,
5034,
1021,
14036,
358,
506,
30591,
358,
326,
3385,
22370,
4213,
18,
225,
3372,
1731,
1021,
3372,
628,
326,
4213,
1566,
23556,
18,
225,
29814,
1566,
1953,
848,
1338,
506,
3723,
635,
3385,
22370,
11632,
578,
326,
525,
23510,
72,
2228,
6174,
18,
19,
5219,
30,
4199,
3796,
4362,
434,
1301,
1347,
326,
1566,
1818,
1704,
5219,
30,
5260,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
225,
445,
10759,
1290,
12,
203,
565,
1758,
2236,
16,
203,
565,
2254,
5034,
1566,
559,
734,
16,
203,
565,
2254,
5034,
460,
16,
203,
565,
2254,
5034,
4213,
14667,
16,
203,
565,
1731,
3372,
203,
225,
262,
3903,
8843,
429,
288,
203,
203,
565,
2583,
12,
203,
1377,
401,
67,
4589,
2016,
63,
4589,
559,
734,
8009,
3700,
8346,
287,
16,
203,
1377,
315,
3700,
2255,
8163,
1677,
2026,
506,
3096,
603,
12433,
6186,
434,
4042,
1758,
6,
203,
565,
11272,
203,
203,
565,
2583,
12,
203,
1377,
401,
67,
1054,
5957,
2498,
63,
4631,
6362,
4589,
559,
734,
8009,
1808,
16,
203,
1377,
315,
17342,
1677,
854,
486,
3260,
16,
1206,
2062,
1566,
1122,
6,
203,
565,
11272,
203,
203,
565,
2254,
5034,
5224,
510,
911,
273,
389,
4589,
2016,
63,
4589,
559,
734,
8009,
15903,
510,
911,
31,
203,
565,
2254,
5034,
525,
23510,
72,
2228,
14667,
273,
389,
4589,
2016,
63,
4589,
559,
734,
8009,
78,
23510,
72,
2228,
14667,
31,
203,
565,
2254,
5034,
384,
911,
273,
1234,
18,
1132,
18,
1717,
12,
7357,
14667,
2934,
1717,
12,
78,
23510,
72,
2228,
14667,
1769,
203,
203,
565,
2583,
12,
203,
1377,
384,
911,
1545,
5224,
510,
911,
16,
203,
1377,
315,
4589,
4991,
279,
6802,
460,
2353,
353,
4551,
2112,
6,
203,
565,
11272,
203,
203,
565,
1731,
1578,
1651,
273,
417,
24410,
581,
5034,
12,
203,
1377,
24126,
18,
3015,
4420,
329,
12,
203,
3639,
1758,
12,
2211,
3631,
203,
3639,
2236,
16,
203,
3639,
1234,
18,
15330,
2
] |
./partial_match/56/0x6d53d13562D8318BB358a032316dE8c988032811/sources/StrategyVSwapWeightLp.sol | / baseToken = 0xf98313f818c53E40Bd758C5276EF4B434463Bec4 (gvValueBUSD-vSwapLP) farmingToken = 0x4f0ed527e8A95ecAA132Af214dFd41F30b361600 (vSwap) targetCompound = 0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56 (BUSD) token0 = 0x0610C2d9F6EbC40078cf081e2D1C4252dD50ad15 (gvValue) token1 = 0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56 (BUSD) | contract StrategyVSwapWeightLp is StrategyBase {
address public farmPool;
uint256 public poolId;
address public token0;
address public token1;
function initialize(
address _baseToken,
address _farmingToken,
address _farmPool,
uint256 _poolId,
address _targetCompound,
uint256 _token0Weight,
address _token0,
address _token1,
address _controller
) public {
require(_initialized == false, "Strategy: Initialize must be false.");
initialize(_baseToken, _farmingToken, _controller, _targetCompound);
farmPool = _farmPool;
poolId = _poolId;
token0 = _token0;
token0Weight = _token0Weight;
token1Weight = 100 - _token0Weight;
token1 = _token1;
IERC20(baseToken).safeApprove(address(farmPool), type(uint256).max);
if (token0 != farmingToken && token0 != targetCompoundToken) {
IERC20(token0).safeApprove(address(unirouter), type(uint256).max);
IERC20(token0).safeApprove(address(vSwaprouter), type(uint256).max);
}
if (token1 != farmingToken && token1 != targetCompoundToken && token1 != token0) {
IERC20(token1).safeApprove(address(unirouter), type(uint256).max);
IERC20(token1).safeApprove(address(vSwaprouter), type(uint256).max);
}
_initialized = true;
}
) public {
require(_initialized == false, "Strategy: Initialize must be false.");
initialize(_baseToken, _farmingToken, _controller, _targetCompound);
farmPool = _farmPool;
poolId = _poolId;
token0 = _token0;
token0Weight = _token0Weight;
token1Weight = 100 - _token0Weight;
token1 = _token1;
IERC20(baseToken).safeApprove(address(farmPool), type(uint256).max);
if (token0 != farmingToken && token0 != targetCompoundToken) {
IERC20(token0).safeApprove(address(unirouter), type(uint256).max);
IERC20(token0).safeApprove(address(vSwaprouter), type(uint256).max);
}
if (token1 != farmingToken && token1 != targetCompoundToken && token1 != token0) {
IERC20(token1).safeApprove(address(unirouter), type(uint256).max);
IERC20(token1).safeApprove(address(vSwaprouter), type(uint256).max);
}
_initialized = true;
}
) public {
require(_initialized == false, "Strategy: Initialize must be false.");
initialize(_baseToken, _farmingToken, _controller, _targetCompound);
farmPool = _farmPool;
poolId = _poolId;
token0 = _token0;
token0Weight = _token0Weight;
token1Weight = 100 - _token0Weight;
token1 = _token1;
IERC20(baseToken).safeApprove(address(farmPool), type(uint256).max);
if (token0 != farmingToken && token0 != targetCompoundToken) {
IERC20(token0).safeApprove(address(unirouter), type(uint256).max);
IERC20(token0).safeApprove(address(vSwaprouter), type(uint256).max);
}
if (token1 != farmingToken && token1 != targetCompoundToken && token1 != token0) {
IERC20(token1).safeApprove(address(unirouter), type(uint256).max);
IERC20(token1).safeApprove(address(vSwaprouter), type(uint256).max);
}
_initialized = true;
}
function getName() public pure override returns (string memory) {
return "StrategyVSwapWeightLp";
}
function deposit() public override {
uint256 _baseBal = IERC20(baseToken).balanceOf(address(this));
if (_baseBal > 0) {
IRewardPool(farmPool).deposit(poolId, _baseBal);
emit Deposit(baseToken, _baseBal);
}
}
function deposit() public override {
uint256 _baseBal = IERC20(baseToken).balanceOf(address(this));
if (_baseBal > 0) {
IRewardPool(farmPool).deposit(poolId, _baseBal);
emit Deposit(baseToken, _baseBal);
}
}
function _withdrawSome(uint256 _amount) internal override returns (uint256) {
(uint256 _stakedAmount, ) = IRewardPool(farmPool).userInfo(poolId, address(this));
if (_amount > _stakedAmount) {
_amount = _stakedAmount;
}
uint256 _before = IERC20(baseToken).balanceOf(address(this));
IRewardPool(farmPool).withdraw(poolId, _amount);
uint256 _after = IERC20(baseToken).balanceOf(address(this));
_amount = _after.sub(_before);
return _amount;
}
function _withdrawSome(uint256 _amount) internal override returns (uint256) {
(uint256 _stakedAmount, ) = IRewardPool(farmPool).userInfo(poolId, address(this));
if (_amount > _stakedAmount) {
_amount = _stakedAmount;
}
uint256 _before = IERC20(baseToken).balanceOf(address(this));
IRewardPool(farmPool).withdraw(poolId, _amount);
uint256 _after = IERC20(baseToken).balanceOf(address(this));
_amount = _after.sub(_before);
return _amount;
}
function _withdrawAll() internal override {
(uint256 _stakedAmount, ) = IRewardPool(farmPool).userInfo(poolId, address(this));
IRewardPool(farmPool).withdraw(poolId, _stakedAmount);
}
function claimReward() public override {
IRewardPool(farmPool).deposit(poolId, 0);
}
function _buyWantAndReinvest() internal override {
{
address _targetCompoundToken = targetCompoundToken;
uint256 _targetCompoundBal = IERC20(_targetCompoundToken).balanceOf(address(this));
if (_targetCompoundToken != token0) {
uint256 _compoundToBuyToken0 = _targetCompoundBal.mul(token0Weight).div(100);
_swapTokens(_targetCompoundToken, token0, _compoundToBuyToken0);
}
if (_targetCompoundToken != token1) {
uint256 _compoundToBuyToken1 = _targetCompoundBal.mul(token1Weight).div(100);
_swapTokens(_targetCompoundToken, token1, _compoundToBuyToken1);
}
}
address _baseToken = baseToken;
uint256 _before = IERC20(_baseToken).balanceOf(address(this));
_addLiquidity();
uint256 _after = IERC20(_baseToken).balanceOf(address(this));
if (_after > 0) {
if (_after > _before) {
uint256 _compound = _after.sub(_before);
vault.addNewCompound(_compound, blocksToReleaseCompound);
}
deposit();
}
}
function _buyWantAndReinvest() internal override {
{
address _targetCompoundToken = targetCompoundToken;
uint256 _targetCompoundBal = IERC20(_targetCompoundToken).balanceOf(address(this));
if (_targetCompoundToken != token0) {
uint256 _compoundToBuyToken0 = _targetCompoundBal.mul(token0Weight).div(100);
_swapTokens(_targetCompoundToken, token0, _compoundToBuyToken0);
}
if (_targetCompoundToken != token1) {
uint256 _compoundToBuyToken1 = _targetCompoundBal.mul(token1Weight).div(100);
_swapTokens(_targetCompoundToken, token1, _compoundToBuyToken1);
}
}
address _baseToken = baseToken;
uint256 _before = IERC20(_baseToken).balanceOf(address(this));
_addLiquidity();
uint256 _after = IERC20(_baseToken).balanceOf(address(this));
if (_after > 0) {
if (_after > _before) {
uint256 _compound = _after.sub(_before);
vault.addNewCompound(_compound, blocksToReleaseCompound);
}
deposit();
}
}
function _buyWantAndReinvest() internal override {
{
address _targetCompoundToken = targetCompoundToken;
uint256 _targetCompoundBal = IERC20(_targetCompoundToken).balanceOf(address(this));
if (_targetCompoundToken != token0) {
uint256 _compoundToBuyToken0 = _targetCompoundBal.mul(token0Weight).div(100);
_swapTokens(_targetCompoundToken, token0, _compoundToBuyToken0);
}
if (_targetCompoundToken != token1) {
uint256 _compoundToBuyToken1 = _targetCompoundBal.mul(token1Weight).div(100);
_swapTokens(_targetCompoundToken, token1, _compoundToBuyToken1);
}
}
address _baseToken = baseToken;
uint256 _before = IERC20(_baseToken).balanceOf(address(this));
_addLiquidity();
uint256 _after = IERC20(_baseToken).balanceOf(address(this));
if (_after > 0) {
if (_after > _before) {
uint256 _compound = _after.sub(_before);
vault.addNewCompound(_compound, blocksToReleaseCompound);
}
deposit();
}
}
function _buyWantAndReinvest() internal override {
{
address _targetCompoundToken = targetCompoundToken;
uint256 _targetCompoundBal = IERC20(_targetCompoundToken).balanceOf(address(this));
if (_targetCompoundToken != token0) {
uint256 _compoundToBuyToken0 = _targetCompoundBal.mul(token0Weight).div(100);
_swapTokens(_targetCompoundToken, token0, _compoundToBuyToken0);
}
if (_targetCompoundToken != token1) {
uint256 _compoundToBuyToken1 = _targetCompoundBal.mul(token1Weight).div(100);
_swapTokens(_targetCompoundToken, token1, _compoundToBuyToken1);
}
}
address _baseToken = baseToken;
uint256 _before = IERC20(_baseToken).balanceOf(address(this));
_addLiquidity();
uint256 _after = IERC20(_baseToken).balanceOf(address(this));
if (_after > 0) {
if (_after > _before) {
uint256 _compound = _after.sub(_before);
vault.addNewCompound(_compound, blocksToReleaseCompound);
}
deposit();
}
}
function _buyWantAndReinvest() internal override {
{
address _targetCompoundToken = targetCompoundToken;
uint256 _targetCompoundBal = IERC20(_targetCompoundToken).balanceOf(address(this));
if (_targetCompoundToken != token0) {
uint256 _compoundToBuyToken0 = _targetCompoundBal.mul(token0Weight).div(100);
_swapTokens(_targetCompoundToken, token0, _compoundToBuyToken0);
}
if (_targetCompoundToken != token1) {
uint256 _compoundToBuyToken1 = _targetCompoundBal.mul(token1Weight).div(100);
_swapTokens(_targetCompoundToken, token1, _compoundToBuyToken1);
}
}
address _baseToken = baseToken;
uint256 _before = IERC20(_baseToken).balanceOf(address(this));
_addLiquidity();
uint256 _after = IERC20(_baseToken).balanceOf(address(this));
if (_after > 0) {
if (_after > _before) {
uint256 _compound = _after.sub(_before);
vault.addNewCompound(_compound, blocksToReleaseCompound);
}
deposit();
}
}
function _buyWantAndReinvest() internal override {
{
address _targetCompoundToken = targetCompoundToken;
uint256 _targetCompoundBal = IERC20(_targetCompoundToken).balanceOf(address(this));
if (_targetCompoundToken != token0) {
uint256 _compoundToBuyToken0 = _targetCompoundBal.mul(token0Weight).div(100);
_swapTokens(_targetCompoundToken, token0, _compoundToBuyToken0);
}
if (_targetCompoundToken != token1) {
uint256 _compoundToBuyToken1 = _targetCompoundBal.mul(token1Weight).div(100);
_swapTokens(_targetCompoundToken, token1, _compoundToBuyToken1);
}
}
address _baseToken = baseToken;
uint256 _before = IERC20(_baseToken).balanceOf(address(this));
_addLiquidity();
uint256 _after = IERC20(_baseToken).balanceOf(address(this));
if (_after > 0) {
if (_after > _before) {
uint256 _compound = _after.sub(_before);
vault.addNewCompound(_compound, blocksToReleaseCompound);
}
deposit();
}
}
function _addLiquidity() internal {
address _token0 = token0;
address _token1 = token1;
uint256 _amount0 = IERC20(_token0).balanceOf(address(this));
uint256 _amount1 = IERC20(_token1).balanceOf(address(this));
if (_amount0 > 0 && _amount1 > 0) {
IValueLiquidRouter(vSwaprouter).addLiquidity(baseToken, _token0, _token1, _amount0, _amount1, 0, 0, address(this), block.timestamp + 1);
}
}
function _addLiquidity() internal {
address _token0 = token0;
address _token1 = token1;
uint256 _amount0 = IERC20(_token0).balanceOf(address(this));
uint256 _amount1 = IERC20(_token1).balanceOf(address(this));
if (_amount0 > 0 && _amount1 > 0) {
IValueLiquidRouter(vSwaprouter).addLiquidity(baseToken, _token0, _token1, _amount0, _amount1, 0, 0, address(this), block.timestamp + 1);
}
}
function balanceOfPool() public view override returns (uint256) {
(uint256 amount, ) = IRewardPool(farmPool).userInfo(poolId, address(this));
return amount;
}
function claimable_tokens() external view override returns (address[] memory farmToken, uint256[] memory totalDistributedValue) {
farmToken = new address[](1);
totalDistributedValue = new uint256[](1);
farmToken[0] = farmingToken;
totalDistributedValue[0] = IRewardPool(farmPool).pendingReward(poolId, address(this));
}
function claimable_token() external view override returns (address farmToken, uint256 totalDistributedValue) {
farmToken = farmingToken;
totalDistributedValue = IRewardPool(farmPool).pendingReward(poolId, address(this));
}
function getTargetFarm() external view override returns (address) {
return farmPool;
}
function getTargetPoolId() external view override returns (uint256) {
return poolId;
}
function retireStrat() external onlyStrategist {
IRewardPool(farmPool).emergencyWithdraw(poolId);
uint256 baseBal = IERC20(baseToken).balanceOf(address(this));
IERC20(baseToken).transfer(address(vault), baseBal);
}
function setBlocksToReleaseCompound(uint256 _blocks) external onlyStrategist {
blocksToReleaseCompound = _blocks;
}
function setFarmPoolContract(address _farmPool) external onlyStrategist {
farmPool = _farmPool;
}
function setPoolId(uint256 _poolId) external onlyStrategist {
poolId = _poolId;
}
function setTokenLp(
address _token0,
address _token1,
uint256 _token0Weight
) external onlyStrategist {
token0 = _token0;
token0Weight = _token0Weight;
token1Weight = 100 - _token0Weight;
token1 = _token1;
if (token0 != farmingToken && token0 != targetCompoundToken) {
IERC20(token0).safeApprove(address(unirouter), type(uint256).max);
IERC20(token0).safeApprove(address(vSwaprouter), type(uint256).max);
}
if (token1 != farmingToken && token1 != targetCompoundToken && token1 != token0) {
IERC20(token1).safeApprove(address(unirouter), type(uint256).max);
IERC20(token1).safeApprove(address(vSwaprouter), type(uint256).max);
}
}
function setTokenLp(
address _token0,
address _token1,
uint256 _token0Weight
) external onlyStrategist {
token0 = _token0;
token0Weight = _token0Weight;
token1Weight = 100 - _token0Weight;
token1 = _token1;
if (token0 != farmingToken && token0 != targetCompoundToken) {
IERC20(token0).safeApprove(address(unirouter), type(uint256).max);
IERC20(token0).safeApprove(address(vSwaprouter), type(uint256).max);
}
if (token1 != farmingToken && token1 != targetCompoundToken && token1 != token0) {
IERC20(token1).safeApprove(address(unirouter), type(uint256).max);
IERC20(token1).safeApprove(address(vSwaprouter), type(uint256).max);
}
}
function setTokenLp(
address _token0,
address _token1,
uint256 _token0Weight
) external onlyStrategist {
token0 = _token0;
token0Weight = _token0Weight;
token1Weight = 100 - _token0Weight;
token1 = _token1;
if (token0 != farmingToken && token0 != targetCompoundToken) {
IERC20(token0).safeApprove(address(unirouter), type(uint256).max);
IERC20(token0).safeApprove(address(vSwaprouter), type(uint256).max);
}
if (token1 != farmingToken && token1 != targetCompoundToken && token1 != token0) {
IERC20(token1).safeApprove(address(unirouter), type(uint256).max);
IERC20(token1).safeApprove(address(vSwaprouter), type(uint256).max);
}
}
} | 11,071,404 | [
1,
19,
1026,
1345,
4202,
273,
374,
5841,
29,
10261,
3437,
74,
28,
2643,
71,
8643,
41,
7132,
38,
72,
5877,
28,
39,
25,
5324,
26,
26897,
24,
38,
24,
5026,
24,
4449,
38,
557,
24,
261,
75,
90,
620,
3000,
9903,
17,
90,
12521,
14461,
13,
284,
4610,
310,
1345,
273,
374,
92,
24,
74,
20,
329,
25,
5324,
73,
28,
37,
8778,
557,
5284,
22152,
12664,
22,
3461,
72,
27263,
9803,
42,
5082,
70,
5718,
2313,
713,
261,
90,
12521,
13,
1018,
16835,
273,
374,
6554,
29,
73,
27,
1441,
37,
23,
20563,
71,
37,
6162,
5193,
27,
3672,
38,
1727,
71,
25,
2733,
70,
40,
8148,
1880,
72,
6840,
27,
40,
4313,
261,
3000,
9903,
13,
1147,
20,
273,
374,
92,
7677,
2163,
39,
22,
72,
29,
42,
26,
41,
70,
39,
16010,
8285,
8522,
6840,
21,
73,
22,
40,
21,
39,
24,
2947,
22,
72,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
19736,
58,
12521,
6544,
48,
84,
353,
19736,
2171,
288,
203,
203,
565,
1758,
1071,
284,
4610,
2864,
31,
203,
565,
2254,
5034,
1071,
2845,
548,
31,
203,
203,
565,
1758,
1071,
1147,
20,
31,
203,
565,
1758,
1071,
1147,
21,
31,
203,
203,
565,
445,
4046,
12,
203,
3639,
1758,
389,
1969,
1345,
16,
203,
3639,
1758,
389,
74,
4610,
310,
1345,
16,
203,
3639,
1758,
389,
74,
4610,
2864,
16,
203,
3639,
2254,
5034,
389,
6011,
548,
16,
203,
3639,
1758,
389,
3299,
16835,
16,
203,
3639,
2254,
5034,
389,
2316,
20,
6544,
16,
203,
3639,
1758,
389,
2316,
20,
16,
203,
3639,
1758,
389,
2316,
21,
16,
203,
3639,
1758,
389,
5723,
203,
203,
565,
262,
1071,
288,
203,
3639,
2583,
24899,
13227,
422,
629,
16,
315,
4525,
30,
9190,
1297,
506,
629,
1199,
1769,
203,
3639,
4046,
24899,
1969,
1345,
16,
389,
74,
4610,
310,
1345,
16,
389,
5723,
16,
389,
3299,
16835,
1769,
203,
3639,
284,
4610,
2864,
273,
389,
74,
4610,
2864,
31,
203,
3639,
2845,
548,
273,
389,
6011,
548,
31,
203,
3639,
1147,
20,
273,
389,
2316,
20,
31,
203,
3639,
1147,
20,
6544,
273,
389,
2316,
20,
6544,
31,
203,
3639,
1147,
21,
6544,
273,
2130,
300,
389,
2316,
20,
6544,
31,
203,
3639,
1147,
21,
273,
389,
2316,
21,
31,
203,
203,
3639,
467,
654,
39,
3462,
12,
1969,
1345,
2934,
4626,
12053,
537,
12,
2867,
12,
74,
4610,
2864,
3631,
618,
12,
11890,
5034,
2934,
1896,
1769,
203,
3639,
309,
261,
2316,
2
] |
pragma solidity ^0.4.24;
import "./VANMToken.sol";
contract VANMPresale is Ownable {
using SafeMath for uint256;
//Variables
uint256 public presaleStartsAt;
uint256 public presaleEndsAt;
uint256 public presaleRate;
uint256 public weiRaised;
address public presaleWallet;
address public tokenAddress;
VANMToken public token;
//Load whitelist
mapping(address => bool) public whitelist;
//Modifiers
//Only during presale
modifier whilePresale {
require(block.timestamp >= presaleStartsAt && block.timestamp <= presaleEndsAt);
_;
}
//Presale has to be over
modifier notBeforePresaleEnds {
require(block.timestamp > presaleEndsAt);
_;
}
//Recipient has to be whitelisted
modifier isWhitelisted(address _to) {
require(whitelist[_to]);
_;
}
//Events
event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount);
event AmountRaised(address beneficiary, uint amountRaised);
event WalletChanged(address _wallet);
//Constructor
constructor() public {
//17.11.2018 00:00 UTC
presaleStartsAt = 1542412800;
//31.12.2018 00:00 UTC
presaleEndsAt = 1546214400;
//Amount of token per wei
presaleRate = 2600;
//Amount of raised Funds in wei
weiRaised = 0;
//Wallet for raised presale funds
presaleWallet = 0xedaFdA45fedcCE4D2b81e173F1D2F21557E97aA5;
//VANM token address
tokenAddress = 0x0d155aaa5C94086bCe0Ad0167EE4D55185F02943;
token = VANMToken(tokenAddress);
}
//External functions
//Add one address to whitelist
function addToWhitelist(address _to) external onlyOwner {
whitelist[_to] = true;
}
//Add multiple addresses to whitelist
function addManyToWhitelist(address[] _to) external onlyOwner {
for (uint256 i = 0; i < _to.length; i++) {
whitelist[_to[i]] = true;
}
}
//Remove one address from whitelist
function removeFromWhitelist(address _to) external onlyOwner {
whitelist[_to] = false;
}
//Remove multiple addresses from whitelist
function removeManyFromWhitelist(address[] _to) external onlyOwner {
for (uint256 i = 0; i < _to.length; i++) {
whitelist[_to[i]] = false;
}
}
//Change presale wallet
function changeWallet(address _presaleWallet) external onlyOwner {
presaleWallet = _presaleWallet;
emit WalletChanged(_presaleWallet);
}
//Close the presale
//Remaining tokens will be transferred to crowdsale
function closePresale() external notBeforePresaleEnds onlyOwner returns (bool) {
emit AmountRaised(presaleWallet, weiRaised);
token.finalizePresale();
return true;
}
//Public functions
//Check if presale has closed
function presaleHasClosed() public view returns (bool) {
return block.timestamp > presaleEndsAt;
}
//Buy tokens by sending ETH to the contract
function () public payable {
buyTokens(msg.sender);
}
//Buy tokens and send it to an address
function buyTokens(address _to) public
whilePresale
isWhitelisted (_to)
payable {
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount * presaleRate;
weiRaised = weiRaised.add(weiAmount);
presaleWallet.transfer(weiAmount);
if (!token.transferFromPresale(_to, tokens)) {
revert();
}
emit TokenPurchase(_to, weiAmount, tokens);
}
//Recover ERC20 tokens
function transferAnyERC20Token(address ERC20Address, uint tokens) public onlyOwner returns (bool success) {
return ERC20(ERC20Address).transfer(owner, tokens);
}
}
| Change presale wallet | function changeWallet(address _presaleWallet) external onlyOwner {
presaleWallet = _presaleWallet;
emit WalletChanged(_presaleWallet);
}
| 12,957,071 | [
1,
3043,
4075,
5349,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2549,
16936,
12,
2867,
389,
12202,
5349,
16936,
13,
3903,
1338,
5541,
288,
203,
3639,
4075,
5349,
16936,
273,
389,
12202,
5349,
16936,
31,
203,
3639,
3626,
20126,
5033,
24899,
12202,
5349,
16936,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.0;
/*
Temporary Hash Registrar
========================
This is a simplified version of a hash registrar. It is purporsefully limited:
names cannot be six letters or shorter, new auctions will stop after 4 years
and all ether still locked after 8 years will become unreachable.
The plan is to test the basic features and then move to a new contract in at most
2 years, when some sort of renewal mechanism will be enabled.
*/
contract AbstractENS {
function owner(bytes32 node) constant returns(address);
function resolver(bytes32 node) constant returns(address);
function ttl(bytes32 node) constant returns(uint64);
function setOwner(bytes32 node, address owner);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner);
function setResolver(bytes32 node, address resolver);
function setTTL(bytes32 node, uint64 ttl);
event Transfer(bytes32 indexed node, address owner);
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
event NewResolver(bytes32 indexed node, address resolver);
event NewTTL(bytes32 indexed node, uint64 ttl);
}
/**
* @title Deed to hold ether in exchange for ownership of a node
* @dev The deed can be controlled only by the registrar and can only send ether back to the owner.
*/
contract Deed {
address public registrar;
address constant burn = 0xdead;
uint public creationDate;
address public owner;
address public previousOwner;
uint public value;
event OwnerChanged(address newOwner);
event DeedClosed();
bool active;
modifier onlyRegistrar {
if (msg.sender != registrar) throw;
_;
}
modifier onlyActive {
if (!active) throw;
_;
}
function Deed(uint _value) {
registrar = msg.sender;
creationDate = now;
active = true;
value = _value;
}
function setOwner(address newOwner) onlyRegistrar {
// so contracts can check who sent them the ownership
previousOwner = owner;
owner = newOwner;
OwnerChanged(newOwner);
}
function setRegistrar(address newRegistrar) onlyRegistrar {
registrar = newRegistrar;
}
function setBalance(uint newValue) onlyRegistrar onlyActive payable {
// Check if it has enough balance to set the value
if (value < newValue) throw;
value = newValue;
// Send the difference to the owner
if (!owner.send(this.balance - newValue)) throw;
}
/**
* @dev Close a deed and refund a specified fraction of the bid value
* @param refundRatio The amount*1/1000 to refund
*/
function closeDeed(uint refundRatio) onlyRegistrar onlyActive {
active = false;
if (! burn.send(((1000 - refundRatio) * this.balance)/1000)) throw;
DeedClosed();
destroyDeed();
}
/**
* @dev Close a deed and refund a specified fraction of the bid value
*/
function destroyDeed() {
if (active) throw;
if(owner.send(this.balance))
selfdestruct(burn);
}
// The default function just receives an amount
function () payable {}
}
/**
* @title Registrar
* @dev The registrar handles the auction process for each subnode of the node it owns.
*/
contract Registrar {
AbstractENS public ens;
bytes32 public rootNode;
mapping (bytes32 => entry) _entries;
mapping (address => mapping(bytes32 => Deed)) public sealedBids;
enum Mode { Open, Auction, Owned, Forbidden, Reveal }
uint32 constant auctionLength = 5 days;
uint32 constant revealPeriod = 48 hours;
uint32 constant initialAuctionPeriod = 4 weeks;
uint constant minPrice = 0.01 ether;
uint public registryStarted;
event AuctionStarted(bytes32 indexed hash, uint registrationDate);
event NewBid(bytes32 indexed hash, address indexed bidder, uint deposit);
event BidRevealed(bytes32 indexed hash, address indexed owner, uint value, uint8 status);
event HashRegistered(bytes32 indexed hash, address indexed owner, uint value, uint registrationDate);
event HashReleased(bytes32 indexed hash, uint value);
event HashInvalidated(bytes32 indexed hash, string indexed name, uint value, uint registrationDate);
struct entry {
Deed deed;
uint registrationDate;
uint value;
uint highestBid;
}
// State transitions for names:
// Open -> Auction (startAuction)
// Auction -> Reveal
// Reveal -> Owned
// Reveal -> Open (if nobody bid)
// Owned -> Forbidden (invalidateName)
// Owned -> Open (releaseDeed)
function state(bytes32 _hash) constant returns (Mode) {
var entry = _entries[_hash];
if(now < entry.registrationDate) {
if(now < entry.registrationDate - revealPeriod) {
return Mode.Auction;
} else {
return Mode.Reveal;
}
} else {
if(entry.highestBid == 0) {
return Mode.Open;
} else if(entry.deed == Deed(0)) {
return Mode.Forbidden;
} else {
return Mode.Owned;
}
}
}
modifier inState(bytes32 _hash, Mode _state) {
if(state(_hash) != _state) throw;
_;
}
modifier onlyOwner(bytes32 _hash) {
if (state(_hash) != Mode.Owned || msg.sender != _entries[_hash].deed.owner()) throw;
_;
}
modifier registryOpen() {
if(now < registryStarted || now > registryStarted + 4 years || ens.owner(rootNode) != address(this)) throw;
_;
}
function entries(bytes32 _hash) constant returns (Mode, address, uint, uint, uint) {
entry h = _entries[_hash];
return (state(_hash), h.deed, h.registrationDate, h.value, h.highestBid);
}
/**
* @dev Constructs a new Registrar, with the provided address as the owner of the root node.
* @param _ens The address of the ENS
* @param _rootNode The hash of the rootnode.
*/
function Registrar(address _ens, bytes32 _rootNode, uint _startDate) {
ens = AbstractENS(_ens);
rootNode = _rootNode;
registryStarted = _startDate > 0 ? _startDate : now;
}
/**
* @dev Returns the maximum of two unsigned integers
* @param a A number to compare
* @param b A number to compare
* @return The maximum of two unsigned integers
*/
function max(uint a, uint b) internal constant returns (uint max) {
if (a > b)
return a;
else
return b;
}
/**
* @dev Returns the minimum of two unsigned integers
* @param a A number to compare
* @param b A number to compare
* @return The minimum of two unsigned integers
*/
function min(uint a, uint b) internal constant returns (uint min) {
if (a < b)
return a;
else
return b;
}
/**
* @dev Returns the length of a given string
* @param s The string to measure the length of
* @return The length of the input string
*/
function strlen(string s) internal constant returns (uint) {
// Starting here means the LSB will be the byte we care about
uint ptr;
uint end;
assembly {
ptr := add(s, 1)
end := add(mload(s), ptr)
}
for (uint len = 0; ptr < end; len++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
return len;
}
/**
* @dev Start an auction for an available hash
*
* Anyone can start an auction by sending an array of hashes that they want to bid for.
* Arrays are sent so that someone can open up an auction for X dummy hashes when they
* are only really interested in bidding for one. This will increase the cost for an
* attacker to simply bid blindly on all new auctions. Dummy auctions that are
* open but not bid on are closed after a week.
*
* @param _hash The hash to start an auction on
*/
function startAuction(bytes32 _hash) inState(_hash, Mode.Open) registryOpen() {
entry newAuction = _entries[_hash];
// for the first month of the registry, make longer auctions
newAuction.registrationDate = max(now + auctionLength, registryStarted + initialAuctionPeriod);
newAuction.value = 0;
newAuction.highestBid = 0;
AuctionStarted(_hash, newAuction.registrationDate);
}
/**
* @dev Start multiple auctions for better anonymity
* @param _hashes An array of hashes, at least one of which you presumably want to bid on
*/
function startAuctions(bytes32[] _hashes) {
for (uint i = 0; i < _hashes.length; i ++ ) {
startAuction(_hashes[i]);
}
}
/**
* @dev Hash the values required for a secret bid
* @param hash The node corresponding to the desired namehash
* @param owner The address which will own the
* @param value The bid amount
* @param salt A random value to ensure secrecy of the bid
* @return The hash of the bid values
*/
function shaBid(bytes32 hash, address owner, uint value, bytes32 salt) constant returns (bytes32 sealedBid) {
return sha3(hash, owner, value, salt);
}
/**
* @dev Submit a new sealed bid on a desired hash in a blind auction
*
* Bids are sent by sending a message to the main contract with a hash and an amount. The hash
* contains information about the bid, including the bidded hash, the bid amount, and a random
* salt. Bids are not tied to any one auction until they are revealed. The value of the bid
* itself can be masqueraded by sending more than the value of your actual bid. This is
* followed by a 24h reveal period. Bids revealed after this period will be burned and the ether unrecoverable.
* Since this is an auction, it is expected that most public hashes, like known domains and common dictionary
* words, will have multiple bidders pushing the price up.
*
* @param sealedBid A sealedBid, created by the shaBid function
*/
function newBid(bytes32 sealedBid) payable {
if (address(sealedBids[msg.sender][sealedBid]) > 0 ) throw;
if (msg.value < minPrice) throw;
// creates a new hash contract with the owner
Deed newBid = new Deed(msg.value);
sealedBids[msg.sender][sealedBid] = newBid;
NewBid(sealedBid, msg.sender, msg.value);
if (!newBid.send(msg.value)) throw;
}
/**
* @dev Submit the properties of a bid to reveal them
* @param _hash The node in the sealedBid
* @param _owner The address in the sealedBid
* @param _value The bid amount in the sealedBid
* @param _salt The sale in the sealedBid
*/
function unsealBid(bytes32 _hash, address _owner, uint _value, bytes32 _salt) {
bytes32 seal = shaBid(_hash, _owner, _value, _salt);
Deed bid = sealedBids[msg.sender][seal];
if (address(bid) == 0 ) throw;
sealedBids[msg.sender][seal] = Deed(0);
bid.setOwner(_owner);
entry h = _entries[_hash];
uint actualValue = min(_value, bid.value());
bid.setBalance(actualValue);
var auctionState = state(_hash);
if(auctionState == Mode.Owned) {
// Too late! Bidder loses their bid. Get's 0.5% back.
bid.closeDeed(5);
BidRevealed(_hash, _owner, actualValue, 1);
} else if(auctionState != Mode.Reveal) {
// Invalid phase
throw;
} else if (_value < minPrice || bid.creationDate() > h.registrationDate - revealPeriod) {
// Bid too low or too late, refund 99.5%
bid.closeDeed(995);
BidRevealed(_hash, _owner, actualValue, 0);
} else if (_value > h.highestBid) {
// new winner
// cancel the other bid, refund 99.5%
if(address(h.deed) != 0) {
Deed previousWinner = h.deed;
previousWinner.closeDeed(995);
}
// set new winner
// per the rules of a vickery auction, the value becomes the previous highestBid
h.value = h.highestBid;
h.highestBid = actualValue;
h.deed = bid;
BidRevealed(_hash, _owner, actualValue, 2);
} else if (_value > h.value) {
// not winner, but affects second place
h.value = actualValue;
bid.closeDeed(995);
BidRevealed(_hash, _owner, actualValue, 3);
} else {
// bid doesn't affect auction
bid.closeDeed(995);
BidRevealed(_hash, _owner, actualValue, 4);
}
}
/**
* @dev Cancel a bid
* @param seal The value returned by the shaBid function
*/
function cancelBid(address bidder, bytes32 seal) {
Deed bid = sealedBids[bidder][seal];
// If the bid hasn't been revealed after any possible auction date, then close it
if (address(bid) == 0
|| now < bid.creationDate() + initialAuctionPeriod
|| bid.owner() > 0) throw;
// Send the canceller 0.5% of the bid, and burn the rest.
bid.setOwner(msg.sender);
bid.closeDeed(5);
sealedBids[bidder][seal] = Deed(0);
BidRevealed(seal, bidder, 0, 5);
}
/**
* @dev Finalize an auction after the registration date has passed
* @param _hash The hash of the name the auction is for
*/
function finalizeAuction(bytes32 _hash) onlyOwner(_hash) {
entry h = _entries[_hash];
h.value = max(h.value, minPrice);
// Assign the owner in ENS
ens.setSubnodeOwner(rootNode, _hash, h.deed.owner());
Deed deedContract = h.deed;
deedContract.setBalance(h.value);
HashRegistered(_hash, deedContract.owner(), h.value, h.registrationDate);
}
/**
* @dev The owner of a domain may transfer it to someone else at any time.
* @param _hash The node to transfer
* @param newOwner The address to transfer ownership to
*/
function transfer(bytes32 _hash, address newOwner) onlyOwner(_hash) {
entry h = _entries[_hash];
h.deed.setOwner(newOwner);
ens.setSubnodeOwner(rootNode, _hash, newOwner);
}
/**
* @dev After some time, the owner can release the property and get their ether back
* @param _hash The node to release
*/
function releaseDeed(bytes32 _hash) onlyOwner(_hash) {
entry h = _entries[_hash];
Deed deedContract = h.deed;
if (now < h.registrationDate + 1 years
|| now > registryStarted + 8 years) throw;
HashReleased(_hash, h.value);
h.value = 0;
h.highestBid = 0;
h.deed = Deed(0);
ens.setSubnodeOwner(rootNode, _hash, 0);
deedContract.closeDeed(1000);
}
/**
* @dev Submit a name 6 characters long or less. If it has been registered,
* the submitter will earn 50% of the deed value. We are purposefully
* handicapping the simplified registrar as a way to force it into being restructured
* in a few years.
* @param unhashedName An invalid name to search for in the registry.
*
*/
function invalidateName(string unhashedName) inState(sha3(unhashedName), Mode.Owned) {
if (strlen(unhashedName) > 6 ) throw;
bytes32 hash = sha3(unhashedName);
entry h = _entries[hash];
ens.setSubnodeOwner(rootNode, hash, 0);
if(address(h.deed) != 0) {
// Reward the discoverer with 50% of the deed
// The previous owner gets 50%
h.deed.setBalance(h.deed.value()/2);
h.deed.setOwner(msg.sender);
h.deed.closeDeed(1000);
}
HashInvalidated(hash, unhashedName, h.value, h.registrationDate);
h.deed = Deed(0);
}
/**
* @dev Transfers the deed to the current registrar, if different from this one.
* Used during the upgrade process to a permanent registrar.
* @param _hash The name hash to transfer.
*/
function transferRegistrars(bytes32 _hash) onlyOwner(_hash) {
var registrar = ens.owner(rootNode);
if(registrar == address(this))
throw;
entry h = _entries[_hash];
h.deed.setRegistrar(registrar);
}
/**
* @dev Returns a deed created by a previous instance of the registrar.
* @param deed The address of the deed.
*/
function returnDeed(Deed deed) {
// Only return if we own the deed, and it was created before our start date.
if(deed.registrar() != address(this) || deed.creationDate() > registryStarted)
throw;
deed.closeDeed(1000);
}
} | * @dev Transfers the deed to the current registrar, if different from this one. Used during the upgrade process to a permanent registrar. @param _hash The name hash to transfer./ | function transferRegistrars(bytes32 _hash) onlyOwner(_hash) {
var registrar = ens.owner(rootNode);
if(registrar == address(this))
throw;
entry h = _entries[_hash];
h.deed.setRegistrar(registrar);
}
| 12,950,924 | [
1,
1429,
18881,
326,
443,
329,
358,
326,
783,
17450,
297,
16,
309,
3775,
628,
333,
1245,
18,
10286,
4982,
326,
8400,
1207,
358,
279,
16866,
17450,
297,
18,
225,
389,
2816,
1021,
508,
1651,
358,
7412,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
20175,
5913,
12,
3890,
1578,
389,
2816,
13,
1338,
5541,
24899,
2816,
13,
288,
203,
3639,
569,
17450,
297,
273,
19670,
18,
8443,
12,
3085,
907,
1769,
203,
3639,
309,
12,
1574,
3337,
297,
422,
1758,
12,
2211,
3719,
203,
5411,
604,
31,
203,
203,
3639,
1241,
366,
273,
389,
8219,
63,
67,
2816,
15533,
203,
3639,
366,
18,
323,
329,
18,
542,
30855,
12,
1574,
3337,
297,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
contract BBI is ERC20, Ownable {
using SafeMath for uint256;
modifier lockSwap() {
_inSwap = true;
_;
_inSwap = false;
}
modifier liquidityAdd() {
_inLiquidityAdd = true;
_;
_inLiquidityAdd = false;
}
// == CONSTANTS ==
uint256 public constant MAX_SUPPLY = 1_000_000_000 ether;
uint256 public constant BPS_DENOMINATOR = 10_000;
uint256 public constant SNIPE_BLOCKS = 2;
// == LIMITS ==
/// @notice Wallet limit in wei.
uint256 public walletLimit;
/// @notice Buy limit in wei.
uint256 public buyLimit;
/// @notice Cooldown in seconds
uint256 public cooldown = 20;
// == TAXES ==
/// @notice Buy marketingTax in BPS
uint256 public buyMarketingTax = 300;
/// @notice Buy devTax in BPS
uint256 public buyDevTax = 400;
/// @notice Buy autoLiquidityTax in BPS
uint256 public buyAutoLiquidityTax = 200;
/// @notice Buy treasuryTax in BPS
uint256 public buyTreasuryTax = 100;
/// @notice Sell marketingTax in BPS
uint256 public sellMarketingTax = 900;
/// @notice Sell devTax in BPS
uint256 public sellDevTax = 1000;
/// @notice Sell autoLiquidityTax in BPS
uint256 public sellAutoLiquidityTax = 400;
/// @notice Sell treasuryTax in BPS
uint256 public sellTreasuryTax = 200;
/// @notice address that marketingTax is sent to
address payable public marketingTaxWallet;
/// @notice address that devTax is sent to
address payable public devTaxWallet;
/// @notice address that treasuryTax is sent to
address payable public treasuryTaxWallet;
/// @notice tokens that are allocated for marketingTax tax
uint256 public totalMarketingTax;
/// @notice tokens that are allocated for devTax tax
uint256 public totalDevTax;
/// @notice tokens that are allocated for auto liquidity tax
uint256 public totalAutoLiquidityTax;
/// @notice tokens that are allocated for treasury tax
uint256 public totalTreasuryTax;
// == FLAGS ==
/// @notice flag indicating Uniswap trading status
bool public tradingActive = false;
/// @notice flag indicating swapAll enabled
bool public swapFees = true;
// == UNISWAP ==
IUniswapV2Router02 public router = IUniswapV2Router02(address(0));
address public pair;
// == WALLET STATUSES ==
/// @notice Maps each wallet to their tax exlcusion status
mapping(address => bool) public taxExcluded;
/// @notice Maps each wallet to the last timestamp they bought
mapping(address => uint256) public lastBuy;
/// @notice Maps each wallet to their blacklist status
mapping(address => bool) public blacklist;
/// @notice Maps each wallet to their whitelist status on buy limit
mapping(address => bool) public walletLimitWhitelist;
// == MISC ==
/// @notice Block when trading is first enabled
uint256 public tradingBlock;
// == INTERNAL ==
uint256 internal _totalSupply = 0;
bool internal _inSwap = false;
bool internal _inLiquidityAdd = false;
mapping(address => uint256) private _balances;
event MarketingTaxWalletChanged(address previousWallet, address nextWallet);
event DevTaxWalletChanged(address previousWallet, address nextWallet);
event TreasuryTaxWalletChanged(address previousWallet, address nextWallet);
event BuyMarketingTaxChanged(uint256 previousTax, uint256 nextTax);
event SellMarketingTaxChanged(uint256 previousTax, uint256 nextTax);
event BuyDevTaxChanged(uint256 previousTax, uint256 nextTax);
event SellDevTaxChanged(uint256 previousTax, uint256 nextTax);
event BuyAutoLiquidityTaxChanged(uint256 previousTax, uint256 nextTax);
event SellAutoLiquidityTaxChanged(uint256 previousTax, uint256 nextTax);
event BuyTreasuryTaxChanged(uint256 previousTax, uint256 nextTax);
event SellTreasuryTaxChanged(uint256 previousTax, uint256 nextTax);
event MarketingTaxRescued(uint256 amount);
event DevTaxRescued(uint256 amount);
event AutoLiquidityTaxRescued(uint256 amount);
event TreasuryTaxRescued(uint256 amount);
event TradingActiveChanged(bool enabled);
event TaxExclusionChanged(address user, bool taxExcluded);
event MaxTransferChanged(uint256 previousMax, uint256 nextMax);
event BuyLimitChanged(uint256 previousMax, uint256 nextMax);
event WalletLimitChanged(uint256 previousMax, uint256 nextMax);
event CooldownChanged(uint256 previousCooldown, uint256 nextCooldown);
event BlacklistUpdated(address user, bool previousStatus, bool nextStatus);
event SwapFeesChanged(bool previousStatus, bool nextStatus);
event WalletLimitWhitelistUpdated(
address user,
bool previousStatus,
bool nextStatus
);
constructor(
address _factory,
address _router,
uint256 _buyLimit,
uint256 _walletLimit,
address payable _marketingTaxWallet,
address payable _devTaxWallet,
address payable _treasuryTaxWallet
) ERC20("Butkus Balboa Inu", "BBI") Ownable() {
taxExcluded[owner()] = true;
taxExcluded[address(0)] = true;
taxExcluded[_marketingTaxWallet] = true;
taxExcluded[_devTaxWallet] = true;
taxExcluded[address(this)] = true;
buyLimit = _buyLimit;
walletLimit = _walletLimit;
marketingTaxWallet = _marketingTaxWallet;
devTaxWallet = _devTaxWallet;
treasuryTaxWallet = _treasuryTaxWallet;
router = IUniswapV2Router02(_router);
IUniswapV2Factory uniswapContract = IUniswapV2Factory(_factory);
pair = uniswapContract.createPair(address(this), router.WETH());
_updateWalletLimitWhitelist(address(this), true);
_updateWalletLimitWhitelist(pair, true);
}
/// @notice Change the address of the buyback wallet
/// @param _marketingTaxWallet The new address of the buyback wallet
function setMarketingTaxWallet(address payable _marketingTaxWallet)
external
onlyOwner
{
emit MarketingTaxWalletChanged(marketingTaxWallet, _marketingTaxWallet);
marketingTaxWallet = _marketingTaxWallet;
}
/// @notice Change the address of the devTax wallet
/// @param _devTaxWallet The new address of the devTax wallet
function setDevTaxWallet(address payable _devTaxWallet) external onlyOwner {
emit DevTaxWalletChanged(devTaxWallet, _devTaxWallet);
devTaxWallet = _devTaxWallet;
}
/// @notice Change the address of the treasuryTax wallet
/// @param _treasuryTaxWallet The new address of the treasuryTax wallet
function setTreasuryTaxWallet(address payable _treasuryTaxWallet)
external
onlyOwner
{
emit TreasuryTaxWalletChanged(treasuryTaxWallet, _treasuryTaxWallet);
treasuryTaxWallet = _treasuryTaxWallet;
}
/// @notice Change the buy marketingTax rate
/// @param _buyMarketingTax The new buy marketingTax rate
function setBuyMarketingTax(uint256 _buyMarketingTax) external onlyOwner {
require(
_buyMarketingTax <= BPS_DENOMINATOR,
"_buyMarketingTax cannot exceed BPS_DENOMINATOR"
);
emit BuyMarketingTaxChanged(buyMarketingTax, _buyMarketingTax);
buyMarketingTax = _buyMarketingTax;
}
/// @notice Change the sell marketingTax rate
/// @param _sellMarketingTax The new sell marketingTax rate
function setSellMarketingTax(uint256 _sellMarketingTax) external onlyOwner {
require(
_sellMarketingTax <= BPS_DENOMINATOR,
"_sellMarketingTax cannot exceed BPS_DENOMINATOR"
);
emit SellMarketingTaxChanged(sellMarketingTax, _sellMarketingTax);
sellMarketingTax = _sellMarketingTax;
}
/// @notice Change the buy devTax rate
/// @param _buyDevTax The new devTax rate
function setBuyDevTax(uint256 _buyDevTax) external onlyOwner {
require(
_buyDevTax <= BPS_DENOMINATOR,
"_buyDevTax cannot exceed BPS_DENOMINATOR"
);
emit BuyDevTaxChanged(buyDevTax, _buyDevTax);
buyDevTax = _buyDevTax;
}
/// @notice Change the buy devTax rate
/// @param _sellDevTax The new devTax rate
function setSellDevTax(uint256 _sellDevTax) external onlyOwner {
require(
_sellDevTax <= BPS_DENOMINATOR,
"_sellDevTax cannot exceed BPS_DENOMINATOR"
);
emit SellDevTaxChanged(sellDevTax, _sellDevTax);
sellDevTax = _sellDevTax;
}
/// @notice Change the buy autoLiquidityTax rate
/// @param _buyAutoLiquidityTax The new buy autoLiquidityTax rate
function setBuyAutoLiquidityTax(uint256 _buyAutoLiquidityTax)
external
onlyOwner
{
require(
_buyAutoLiquidityTax <= BPS_DENOMINATOR,
"_buyAutoLiquidityTax cannot exceed BPS_DENOMINATOR"
);
emit BuyAutoLiquidityTaxChanged(
buyAutoLiquidityTax,
_buyAutoLiquidityTax
);
buyAutoLiquidityTax = _buyAutoLiquidityTax;
}
/// @notice Change the sell autoLiquidityTax rate
/// @param _sellAutoLiquidityTax The new sell autoLiquidityTax rate
function setSellAutoLiquidityTax(uint256 _sellAutoLiquidityTax)
external
onlyOwner
{
require(
_sellAutoLiquidityTax <= BPS_DENOMINATOR,
"_sellAutoLiquidityTax cannot exceed BPS_DENOMINATOR"
);
emit SellAutoLiquidityTaxChanged(
sellAutoLiquidityTax,
_sellAutoLiquidityTax
);
sellAutoLiquidityTax = _sellAutoLiquidityTax;
}
/// @notice Change the buy treasuryTax rate
/// @param _buyTreasuryTax The new treasuryTax rate
function setBuyTreasuryTax(uint256 _buyTreasuryTax) external onlyOwner {
require(
_buyTreasuryTax <= BPS_DENOMINATOR,
"_buyTreasuryTax cannot exceed BPS_DENOMINATOR"
);
emit BuyTreasuryTaxChanged(buyTreasuryTax, _buyTreasuryTax);
buyTreasuryTax = _buyTreasuryTax;
}
/// @notice Change the buy treasuryTax rate
/// @param _sellTreasuryTax The new treasuryTax rate
function setSellTreasuryTax(uint256 _sellTreasuryTax) external onlyOwner {
require(
_sellTreasuryTax <= BPS_DENOMINATOR,
"_sellTreasuryTax cannot exceed BPS_DENOMINATOR"
);
emit SellTreasuryTaxChanged(sellTreasuryTax, _sellTreasuryTax);
sellTreasuryTax = _sellTreasuryTax;
}
/// @notice Change the cooldown for buys
/// @param _cooldown The new cooldown in seconds
function setCooldown(uint256 _cooldown) external onlyOwner {
emit CooldownChanged(cooldown, _cooldown);
cooldown = _cooldown;
}
/// @notice Rescue BBI from the marketingTax amount
/// @dev Should only be used in an emergency
/// @param _amount The amount of BBI to rescue
/// @param _recipient The recipient of the rescued BBI
function rescueMarketingTaxTokens(uint256 _amount, address _recipient)
external
onlyOwner
{
require(
_amount <= totalMarketingTax,
"Amount cannot be greater than totalMarketingTax"
);
_rawTransfer(address(this), _recipient, _amount);
emit MarketingTaxRescued(_amount);
totalMarketingTax -= _amount;
}
/// @notice Rescue BBI from the devTax amount
/// @dev Should only be used in an emergency
/// @param _amount The amount of BBI to rescue
/// @param _recipient The recipient of the rescued BBI
function rescueDevTaxTokens(uint256 _amount, address _recipient)
external
onlyOwner
{
require(
_amount <= totalDevTax,
"Amount cannot be greater than totalDevTax"
);
_rawTransfer(address(this), _recipient, _amount);
emit DevTaxRescued(_amount);
totalDevTax -= _amount;
}
/// @notice Rescue BBI from the autoLiquidityTax amount
/// @dev Should only be used in an emergency
/// @param _amount The amount of BBI to rescue
/// @param _recipient The recipient of the rescued BBI
function rescueAutoLiquidityTaxTokens(uint256 _amount, address _recipient)
external
onlyOwner
{
require(
_amount <= totalAutoLiquidityTax,
"Amount cannot be greater than totalAutoLiquidityTax"
);
_rawTransfer(address(this), _recipient, _amount);
emit AutoLiquidityTaxRescued(_amount);
totalAutoLiquidityTax -= _amount;
}
/// @notice Rescue BBI from the treasuryTax amount
/// @dev Should only be used in an emergency
/// @param _amount The amount of BBI to rescue
/// @param _recipient The recipient of the rescued BBI
function rescueTreasuryTaxTokens(uint256 _amount, address _recipient)
external
onlyOwner
{
require(
_amount <= totalTreasuryTax,
"Amount cannot be greater than totalTreasuryTax"
);
_rawTransfer(address(this), _recipient, _amount);
emit TreasuryTaxRescued(_amount);
totalTreasuryTax -= _amount;
}
function addLiquidity(uint256 tokens)
external
payable
onlyOwner
liquidityAdd
{
_mint(address(this), tokens);
_approve(address(this), address(router), tokens);
router.addLiquidityETH{value: msg.value}(
address(this),
tokens,
0,
0,
owner(),
// solhint-disable-next-line not-rely-on-time
block.timestamp
);
}
/// @notice Admin function to update a wallet's blacklist status
/// @param user the wallet
/// @param status the new status
function updateBlacklist(address user, bool status)
external
virtual
onlyOwner
{
_updateBlacklist(user, status);
}
function _updateBlacklist(address user, bool status) internal virtual {
emit BlacklistUpdated(user, blacklist[user], status);
blacklist[user] = status;
}
/// @notice Admin function to update a wallet's buy limit status
/// @param user the wallet
/// @param status the new status
function updateWalletLimitWhitelist(address user, bool status)
external
virtual
onlyOwner
{
_updateWalletLimitWhitelist(user, status);
}
function _updateWalletLimitWhitelist(address user, bool status)
internal
virtual
{
emit WalletLimitWhitelistUpdated(
user,
walletLimitWhitelist[user],
status
);
walletLimitWhitelist[user] = status;
}
/// @notice Enables or disables trading on Uniswap
function setTradingActive(bool _tradingActive) external onlyOwner {
if (_tradingActive && tradingBlock == 0) {
tradingBlock = block.number;
}
tradingActive = _tradingActive;
emit TradingActiveChanged(_tradingActive);
}
/// @notice Updates tax exclusion status
/// @param _account Account to update the tax exclusion status of
/// @param _taxExcluded If true, exclude taxes for this user
function setTaxExcluded(address _account, bool _taxExcluded)
public
onlyOwner
{
taxExcluded[_account] = _taxExcluded;
emit TaxExclusionChanged(_account, _taxExcluded);
}
/// @notice Updates the max amount allowed to buy
/// @param _buyLimit The new buy limit
function setBuyLimit(uint256 _buyLimit) external onlyOwner {
emit BuyLimitChanged(buyLimit, _buyLimit);
buyLimit = _buyLimit;
}
/// @notice Updates the max amount allowed to be held by a single wallet
/// @param _walletLimit The new max
function setWalletLimit(uint256 _walletLimit) external onlyOwner {
emit WalletLimitChanged(walletLimit, _walletLimit);
walletLimit = _walletLimit;
}
/// @notice Enable or disable whether swap occurs during `_transfer`
/// @param _swapFees If true, enables swap during `_transfer`
function setSwapFees(bool _swapFees) external onlyOwner {
emit SwapFeesChanged(swapFees, _swapFees);
swapFees = _swapFees;
}
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
function _addBalance(address account, uint256 amount) internal {
_balances[account] = _balances[account] + amount;
}
function _subtractBalance(address account, uint256 amount) internal {
_balances[account] = _balances[account] - amount;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(!blacklist[recipient], "Recipient is blacklisted");
if (taxExcluded[sender] || taxExcluded[recipient]) {
_rawTransfer(sender, recipient, amount);
return;
}
// Enforce wallet limits
if (!walletLimitWhitelist[recipient]) {
require(
balanceOf(recipient).add(amount) <= walletLimit,
"Wallet limit exceeded"
);
}
uint256 send = amount;
uint256 marketingTax;
uint256 devTax;
uint256 autoLiquidityTax;
uint256 treasuryTax;
if (sender == pair) {
require(tradingActive, "Trading is not yet active");
require(
balanceOf(recipient).add(amount) <= buyLimit,
"Buy limit exceeded"
);
if (block.number <= tradingBlock + SNIPE_BLOCKS) {
_updateBlacklist(recipient, true);
}
if (cooldown > 0) {
require(
lastBuy[recipient] + cooldown <= block.timestamp,
"Cooldown still active"
);
lastBuy[recipient] = block.timestamp;
}
(
send,
marketingTax,
devTax,
autoLiquidityTax,
treasuryTax
) = _getTaxAmounts(amount, true);
} else if (recipient == pair) {
require(tradingActive, "Trading is not yet active");
if (swapFees) swapAll();
(
send,
marketingTax,
devTax,
autoLiquidityTax,
treasuryTax
) = _getTaxAmounts(amount, false);
}
_rawTransfer(sender, recipient, send);
_takeTaxes(sender, marketingTax, devTax, autoLiquidityTax, treasuryTax);
}
/// @notice Peforms auto liquidity and tax distribution
function swapAll() public lockSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
// Auto-liquidity
uint256 autoLiquidityAmount = totalAutoLiquidityTax.div(2);
uint256 walletTaxes = totalMarketingTax.add(totalDevTax).add(
totalTreasuryTax
);
_approve(
address(this),
address(router),
walletTaxes.add(totalAutoLiquidityTax)
);
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
autoLiquidityAmount.add(walletTaxes),
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
router.addLiquidityETH{value: address(this).balance}(
address(this),
autoLiquidityAmount,
0,
0,
address(0xdead),
block.timestamp
);
totalAutoLiquidityTax = 0;
// Distribute remaining taxes
uint256 contractEth = address(this).balance;
uint256 marketingTaxEth = contractEth.mul(totalMarketingTax).div(
walletTaxes
);
uint256 devTaxEth = contractEth.mul(totalDevTax).div(walletTaxes);
uint256 treasuryTaxEth = contractEth.mul(totalTreasuryTax).div(
walletTaxes
);
totalMarketingTax = 0;
totalDevTax = 0;
totalTreasuryTax = 0;
if (marketingTaxEth > 0) {
marketingTaxWallet.transfer(marketingTaxEth);
}
if (devTaxEth > 0) {
devTaxWallet.transfer(devTaxEth);
}
if (treasuryTaxEth > 0) {
treasuryTaxWallet.transfer(treasuryTaxEth);
}
}
/// @notice Admin function to rescue ETH from the contract
function rescueETH() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
/// @notice Transfers BBI from an account to this contract for taxes
/// @param _account The account to transfer BBI from
/// @param _marketingTaxAmount The amount of marketingTax tax to transfer
/// @param _devTaxAmount The amount of devTax tax to transfer
function _takeTaxes(
address _account,
uint256 _marketingTaxAmount,
uint256 _devTaxAmount,
uint256 _autoLiquidityTaxAmount,
uint256 _treasuryTaxAmount
) internal {
require(_account != address(0), "taxation from the zero address");
uint256 totalAmount = _marketingTaxAmount
.add(_devTaxAmount)
.add(_autoLiquidityTaxAmount)
.add(_treasuryTaxAmount);
_rawTransfer(_account, address(this), totalAmount);
totalMarketingTax += _marketingTaxAmount;
totalDevTax += _devTaxAmount;
totalAutoLiquidityTax += _autoLiquidityTaxAmount;
totalTreasuryTax += _treasuryTaxAmount;
}
/// @notice Get a breakdown of send and tax amounts
/// @param amount The amount to tax in wei
/// @return send The raw amount to send
/// @return marketingTax The raw marketingTax tax amount
/// @return devTax The raw devTax tax amount
function _getTaxAmounts(uint256 amount, bool buying)
internal
view
returns (
uint256 send,
uint256 marketingTax,
uint256 devTax,
uint256 autoLiquidityTax,
uint256 treasuryTax
)
{
if (buying) {
marketingTax = amount.mul(buyMarketingTax).div(BPS_DENOMINATOR);
devTax = amount.mul(buyDevTax).div(BPS_DENOMINATOR);
autoLiquidityTax = amount.mul(buyAutoLiquidityTax).div(
BPS_DENOMINATOR
);
treasuryTax = amount.mul(buyTreasuryTax).div(BPS_DENOMINATOR);
} else {
marketingTax = amount.mul(sellMarketingTax).div(BPS_DENOMINATOR);
devTax = amount.mul(sellDevTax).div(BPS_DENOMINATOR);
autoLiquidityTax = amount.mul(sellAutoLiquidityTax).div(
BPS_DENOMINATOR
);
treasuryTax = amount.mul(sellTreasuryTax).div(BPS_DENOMINATOR);
}
send = amount.sub(marketingTax).sub(devTax).sub(autoLiquidityTax).sub(
treasuryTax
);
}
// modified from OpenZeppelin ERC20
function _rawTransfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "transfer from the zero address");
require(recipient != address(0), "transfer to the zero address");
uint256 senderBalance = balanceOf(sender);
require(senderBalance >= amount, "transfer amount exceeds balance");
unchecked {
_subtractBalance(sender, amount);
}
_addBalance(recipient, amount);
emit Transfer(sender, recipient, amount);
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function _mint(address account, uint256 amount) internal override {
require(_totalSupply.add(amount) <= MAX_SUPPLY, "Max supply exceeded");
_totalSupply += amount;
_addBalance(account, amount);
emit Transfer(address(0), account, amount);
}
function mint(address account, uint256 amount) external onlyOwner {
_mint(account, amount);
}
function airdrop(address[] memory accounts, uint256[] memory amounts)
external
onlyOwner
{
require(accounts.length == amounts.length, "array lengths must match");
for (uint256 i = 0; i < accounts.length; i++) {
_mint(accounts[i], amounts[i]);
}
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
} | @notice Change the buy treasuryTax rate @param _sellTreasuryTax The new treasuryTax rate | function setSellTreasuryTax(uint256 _sellTreasuryTax) external onlyOwner {
require(
_sellTreasuryTax <= BPS_DENOMINATOR,
"_sellTreasuryTax cannot exceed BPS_DENOMINATOR"
);
emit SellTreasuryTaxChanged(sellTreasuryTax, _sellTreasuryTax);
sellTreasuryTax = _sellTreasuryTax;
}
| 1,608,852 | [
1,
3043,
326,
30143,
9787,
345,
22498,
7731,
4993,
225,
389,
87,
1165,
56,
266,
345,
22498,
7731,
1021,
394,
9787,
345,
22498,
7731,
4993,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
13928,
1165,
56,
266,
345,
22498,
7731,
12,
11890,
5034,
389,
87,
1165,
56,
266,
345,
22498,
7731,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
389,
87,
1165,
56,
266,
345,
22498,
7731,
1648,
605,
5857,
67,
13296,
1872,
706,
3575,
16,
203,
5411,
4192,
87,
1165,
56,
266,
345,
22498,
7731,
2780,
9943,
605,
5857,
67,
13296,
1872,
706,
3575,
6,
203,
3639,
11272,
203,
3639,
3626,
348,
1165,
56,
266,
345,
22498,
7731,
5033,
12,
87,
1165,
56,
266,
345,
22498,
7731,
16,
389,
87,
1165,
56,
266,
345,
22498,
7731,
1769,
203,
3639,
357,
80,
56,
266,
345,
22498,
7731,
273,
389,
87,
1165,
56,
266,
345,
22498,
7731,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
// BuryLeash is the coolest pit in town. You come in with some Leash, and leave with more! The longer you stay, the more Leash you get.
//
// This contract handles swapping to and from xLeash.
contract BuryLeash is ERC20("xLeash Staked Leash", "xLEASH"){
using SafeMath for uint256;
IERC20 public immutable LEASH;
// Define the Leash token contract
constructor(IERC20 _LEASH) public {
require(address(_LEASH) != address(0), "_LEASH is a zero address");
LEASH = _LEASH;
}
// Enter the doghouse. Pay some LEASHs. Earn some shares.
// Locks Leash and mints xLeash
function enter(uint256 _amount) public {
// Gets the amount of Leash locked in the contract
uint256 totalLeash = LEASH.balanceOf(address(this));
// Gets the amount of xLeash in existence
uint256 totalShares = totalSupply();
// If no xLeash exists, mint it 1:1 to the amount put in
if (totalShares == 0 || totalLeash == 0) {
_mint(msg.sender, _amount);
}
// Calculate and mint the amount of xLeash the Leash is worth. The ratio will change overtime, as xLeash is burned/minted and Leash deposited + gained from fees / withdrawn.
else {
uint256 what = _amount.mul(totalShares).div(totalLeash);
_mint(msg.sender, what);
}
// Lock the Leash in the contract
LEASH.transferFrom(msg.sender, address(this), _amount);
}
// Leave the doghouse. Claim back your LEASHs.
// Unclocks the staked + gained Leash and burns xLeash
function leave(uint256 _share) public {
// Gets the amount of xLeash in existence
uint256 totalShares = totalSupply();
// Calculates the amount of Leash the xLeash is worth
uint256 what = _share.mul(LEASH.balanceOf(address(this))).div(totalShares);
_burn(msg.sender, _share);
LEASH.transfer(msg.sender, what);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
| Leave the doghouse. Claim back your LEASHs. Unclocks the staked + gained Leash and burns xLeash Gets the amount of xLeash in existence Calculates the amount of Leash the xLeash is worth | function leave(uint256 _share) public {
uint256 totalShares = totalSupply();
uint256 what = _share.mul(LEASH.balanceOf(address(this))).div(totalShares);
_burn(msg.sender, _share);
LEASH.transfer(msg.sender, what);
}
| 12,134,753 | [
1,
21300,
326,
302,
717,
13028,
18,
18381,
1473,
3433,
5380,
10793,
87,
18,
1351,
18517,
87,
326,
384,
9477,
397,
314,
8707,
3519,
961,
471,
18305,
87,
619,
1682,
961,
11881,
326,
3844,
434,
619,
1682,
961,
316,
15782,
26128,
326,
3844,
434,
3519,
961,
326,
619,
1682,
961,
353,
26247,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8851,
12,
11890,
5034,
389,
14419,
13,
1071,
288,
203,
3639,
2254,
5034,
2078,
24051,
273,
2078,
3088,
1283,
5621,
203,
203,
3639,
2254,
5034,
4121,
273,
389,
14419,
18,
16411,
12,
900,
10793,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
2934,
2892,
12,
4963,
24051,
1769,
203,
3639,
389,
70,
321,
12,
3576,
18,
15330,
16,
389,
14419,
1769,
203,
3639,
5380,
10793,
18,
13866,
12,
3576,
18,
15330,
16,
4121,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-27
*/
// SPDX-License-Identifier: BUSL-1.1
// File: @uniswap/lib/contracts/libraries/TransferHelper.sol
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/interfaces/IDMMFactory.sol
pragma solidity 0.6.12;
interface IDMMFactory {
function createPool(
IERC20 tokenA,
IERC20 tokenB,
uint32 ampBps
) external returns (address pool);
function setFeeConfiguration(address feeTo, uint16 governmentFeeBps) external;
function setFeeToSetter(address) external;
function getFeeConfiguration() external view returns (address feeTo, uint16 governmentFeeBps);
function feeToSetter() external view returns (address);
function allPools(uint256) external view returns (address pool);
function allPoolsLength() external view returns (uint256);
function getUnamplifiedPool(IERC20 token0, IERC20 token1) external view returns (address);
function getPools(IERC20 token0, IERC20 token1)
external
view
returns (address[] memory _tokenPools);
function isPool(
IERC20 token0,
IERC20 token1,
address pool
) external view returns (bool);
}
// File: contracts/interfaces/IWETH.sol
pragma solidity 0.6.12;
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
// File: contracts/interfaces/IDMMExchangeRouter.sol
pragma solidity 0.6.12;
/// @dev an simple interface for integration dApp to swap
interface IDMMExchangeRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function getAmountsOut(
uint256 amountIn,
address[] calldata poolsPath,
IERC20[] calldata path
) external view returns (uint256[] memory amounts);
function getAmountsIn(
uint256 amountOut,
address[] calldata poolsPath,
IERC20[] calldata path
) external view returns (uint256[] memory amounts);
}
// File: contracts/interfaces/IDMMLiquidityRouter.sol
pragma solidity 0.6.12;
/// @dev an simple interface for integration dApp to contribute liquidity
interface IDMMLiquidityRouter {
/**
* @param tokenA address of token in the pool
* @param tokenB address of token in the pool
* @param pool the address of the pool
* @param amountADesired the amount of tokenA users want to add to the pool
* @param amountBDesired the amount of tokenB users want to add to the pool
* @param amountAMin bounds to the extents to which amountB/amountA can go up
* @param amountBMin bounds to the extents to which amountB/amountA can go down
* @param vReserveRatioBounds bounds to the extents to which vReserveB/vReserveA can go (precision: 2 ** 112)
* @param to Recipient of the liquidity tokens.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function addLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
uint256[2] calldata vReserveRatioBounds,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityNewPool(
IERC20 tokenA,
IERC20 tokenB,
uint32 ampBps,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityNewPoolETH(
IERC20 token,
uint32 ampBps,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
/**
* @param token address of token in the pool
* @param pool the address of the pool
* @param amountTokenDesired the amount of token users want to add to the pool
* @dev msg.value equals to amountEthDesired
* @param amountTokenMin bounds to the extents to which WETH/token can go up
* @param amountETHMin bounds to the extents to which WETH/token can go down
* @param vReserveRatioBounds bounds to the extents to which vReserveB/vReserveA can go (precision: 2 ** 112)
* @param to Recipient of the liquidity tokens.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function addLiquidityETH(
IERC20 token,
address pool,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
uint256[2] calldata vReserveRatioBounds,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
/**
* @param tokenA address of token in the pool
* @param tokenB address of token in the pool
* @param pool the address of the pool
* @param liquidity the amount of lp token users want to burn
* @param amountAMin the minimum token retuned after burning
* @param amountBMin the minimum token retuned after burning
* @param to Recipient of the returned tokens.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function removeLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
/**
* @param tokenA address of token in the pool
* @param tokenB address of token in the pool
* @param pool the address of the pool
* @param liquidity the amount of lp token users want to burn
* @param amountAMin the minimum token retuned after burning
* @param amountBMin the minimum token retuned after burning
* @param to Recipient of the returned tokens.
* @param deadline Unix timestamp after which the transaction will revert.
* @param approveMax whether users permit the router spending max lp token or not.
* @param r s v Signature of user to permit the router spending lp token
*/
function removeLiquidityWithPermit(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
/**
* @param token address of token in the pool
* @param pool the address of the pool
* @param liquidity the amount of lp token users want to burn
* @param amountTokenMin the minimum token retuned after burning
* @param amountETHMin the minimum eth in wei retuned after burning
* @param to Recipient of the returned tokens.
* @param deadline Unix timestamp after which the transaction will revert
*/
function removeLiquidityETH(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
/**
* @param token address of token in the pool
* @param pool the address of the pool
* @param liquidity the amount of lp token users want to burn
* @param amountTokenMin the minimum token retuned after burning
* @param amountETHMin the minimum eth in wei retuned after burning
* @param to Recipient of the returned tokens.
* @param deadline Unix timestamp after which the transaction will revert
* @param approveMax whether users permit the router spending max lp token
* @param r s v signatures of user to permit the router spending lp token.
*/
function removeLiquidityETHWithPermit(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
/**
* @param amountA amount of 1 side token added to the pool
* @param reserveA current reserve of the pool
* @param reserveB current reserve of the pool
* @return amountB amount of the other token added to the pool
*/
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
}
// File: contracts/interfaces/IDMMRouter01.sol
pragma solidity 0.6.12;
/// @dev full interface for router
interface IDMMRouter01 is IDMMExchangeRouter, IDMMLiquidityRouter {
function factory() external pure returns (address);
function weth() external pure returns (IWETH);
}
// File: contracts/interfaces/IDMMRouter02.sol
pragma solidity 0.6.12;
interface IDMMRouter02 is IDMMRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external;
}
// File: contracts/interfaces/IERC20Permit.sol
pragma solidity 0.6.12;
interface IERC20Permit is IERC20 {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File: contracts/interfaces/IDMMPool.sol
pragma solidity 0.6.12;
interface IDMMPool {
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function sync() external;
function getReserves() external view returns (uint112 reserve0, uint112 reserve1);
function getTradeInfo()
external
view
returns (
uint112 _vReserve0,
uint112 _vReserve1,
uint112 reserve0,
uint112 reserve1,
uint256 feeInPrecision
);
function token0() external view returns (IERC20);
function token1() external view returns (IERC20);
function ampBps() external view returns (uint32);
function factory() external view returns (IDMMFactory);
function kLast() external view returns (uint256);
}
// File: contracts/libraries/DMMLibrary.sol
pragma solidity 0.6.12;
library DMMLibrary {
using SafeMath for uint256;
uint256 public constant PRECISION = 1e18;
// returns sorted token addresses, used to handle return values from pools sorted in this order
function sortTokens(IERC20 tokenA, IERC20 tokenB)
internal
pure
returns (IERC20 token0, IERC20 token1)
{
require(tokenA != tokenB, "DMMLibrary: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(address(token0) != address(0), "DMMLibrary: ZERO_ADDRESS");
}
/// @dev fetch the reserves and fee for a pool, used for trading purposes
function getTradeInfo(
address pool,
IERC20 tokenA,
IERC20 tokenB
)
internal
view
returns (
uint256 reserveA,
uint256 reserveB,
uint256 vReserveA,
uint256 vReserveB,
uint256 feeInPrecision
)
{
(IERC20 token0, ) = sortTokens(tokenA, tokenB);
uint256 reserve0;
uint256 reserve1;
uint256 vReserve0;
uint256 vReserve1;
(reserve0, reserve1, vReserve0, vReserve1, feeInPrecision) = IDMMPool(pool).getTradeInfo();
(reserveA, reserveB, vReserveA, vReserveB) = tokenA == token0
? (reserve0, reserve1, vReserve0, vReserve1)
: (reserve1, reserve0, vReserve1, vReserve0);
}
/// @dev fetches the reserves for a pool, used for liquidity adding
function getReserves(
address pool,
IERC20 tokenA,
IERC20 tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(IERC20 token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1) = IDMMPool(pool).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pool reserves, returns an equivalent amount of the other asset
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "DMMLibrary: INSUFFICIENT_AMOUNT");
require(reserveA > 0 && reserveB > 0, "DMMLibrary: INSUFFICIENT_LIQUIDITY");
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pool reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut,
uint256 vReserveIn,
uint256 vReserveOut,
uint256 feeInPrecision
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "DMMLibrary: INSUFFICIENT_INPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "DMMLibrary: INSUFFICIENT_LIQUIDITY");
uint256 amountInWithFee = amountIn.mul(PRECISION.sub(feeInPrecision)).div(PRECISION);
uint256 numerator = amountInWithFee.mul(vReserveOut);
uint256 denominator = vReserveIn.add(amountInWithFee);
amountOut = numerator.div(denominator);
require(reserveOut > amountOut, "DMMLibrary: INSUFFICIENT_LIQUIDITY");
}
// given an output amount of an asset and pool reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut,
uint256 vReserveIn,
uint256 vReserveOut,
uint256 feeInPrecision
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "DMMLibrary: INSUFFICIENT_OUTPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > amountOut, "DMMLibrary: INSUFFICIENT_LIQUIDITY");
uint256 numerator = vReserveIn.mul(amountOut);
uint256 denominator = vReserveOut.sub(amountOut);
amountIn = numerator.div(denominator).add(1);
// amountIn = floor(amountIN *PRECISION / (PRECISION - feeInPrecision));
numerator = amountIn.mul(PRECISION);
denominator = PRECISION.sub(feeInPrecision);
amountIn = numerator.add(denominator - 1).div(denominator);
}
// performs chained getAmountOut calculations on any number of pools
function getAmountsOut(
uint256 amountIn,
address[] memory poolsPath,
IERC20[] memory path
) internal view returns (uint256[] memory amounts) {
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(
uint256 reserveIn,
uint256 reserveOut,
uint256 vReserveIn,
uint256 vReserveOut,
uint256 feeInPrecision
) = getTradeInfo(poolsPath[i], path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(
amounts[i],
reserveIn,
reserveOut,
vReserveIn,
vReserveOut,
feeInPrecision
);
}
}
// performs chained getAmountIn calculations on any number of pools
function getAmountsIn(
uint256 amountOut,
address[] memory poolsPath,
IERC20[] memory path
) internal view returns (uint256[] memory amounts) {
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(
uint256 reserveIn,
uint256 reserveOut,
uint256 vReserveIn,
uint256 vReserveOut,
uint256 feeInPrecision
) = getTradeInfo(poolsPath[i - 1], path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(
amounts[i],
reserveIn,
reserveOut,
vReserveIn,
vReserveOut,
feeInPrecision
);
}
}
}
// File: contracts/periphery/DMMRouter02.sol
pragma solidity 0.6.12;
contract DMMRouter02 is IDMMRouter02 {
using SafeERC20 for IERC20;
using SafeERC20 for IWETH;
using SafeMath for uint256;
uint256 internal constant BPS = 10000;
uint256 internal constant MIN_VRESERVE_RATIO = 0;
uint256 internal constant MAX_VRESERVE_RATIO = 2**256 - 1;
uint256 internal constant Q112 = 2**112;
address public immutable override factory;
IWETH public immutable override weth;
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "DMMRouter: EXPIRED");
_;
}
constructor(address _factory, IWETH _weth) public {
factory = _factory;
weth = _weth;
}
receive() external payable {
assert(msg.sender == address(weth)); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
uint256[2] memory vReserveRatioBounds
) internal virtual view returns (uint256 amountA, uint256 amountB) {
(uint256 reserveA, uint256 reserveB, uint256 vReserveA, uint256 vReserveB, ) = DMMLibrary
.getTradeInfo(pool, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint256 amountBOptimal = DMMLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, "DMMRouter: INSUFFICIENT_B_AMOUNT");
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint256 amountAOptimal = DMMLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, "DMMRouter: INSUFFICIENT_A_AMOUNT");
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
uint256 currentRate = (vReserveB * Q112) / vReserveA;
require(
currentRate >= vReserveRatioBounds[0] && currentRate <= vReserveRatioBounds[1],
"DMMRouter: OUT_OF_BOUNDS_VRESERVE"
);
}
}
function addLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
uint256[2] memory vReserveRatioBounds,
address to,
uint256 deadline
)
public
virtual
override
ensure(deadline)
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
verifyPoolAddress(tokenA, tokenB, pool);
(amountA, amountB) = _addLiquidity(
tokenA,
tokenB,
pool,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
vReserveRatioBounds
);
// using tokenA.safeTransferFrom will get "Stack too deep"
SafeERC20.safeTransferFrom(tokenA, msg.sender, pool, amountA);
SafeERC20.safeTransferFrom(tokenB, msg.sender, pool, amountB);
liquidity = IDMMPool(pool).mint(to);
}
function addLiquidityETH(
IERC20 token,
address pool,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
uint256[2] memory vReserveRatioBounds,
address to,
uint256 deadline
)
public
override
payable
ensure(deadline)
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
)
{
verifyPoolAddress(token, weth, pool);
(amountToken, amountETH) = _addLiquidity(
token,
weth,
pool,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin,
vReserveRatioBounds
);
token.safeTransferFrom(msg.sender, pool, amountToken);
weth.deposit{value: amountETH}();
weth.safeTransfer(pool, amountETH);
liquidity = IDMMPool(pool).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) {
TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
}
function addLiquidityNewPool(
IERC20 tokenA,
IERC20 tokenB,
uint32 ampBps,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
override
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
address pool;
if (ampBps == BPS) {
pool = IDMMFactory(factory).getUnamplifiedPool(tokenA, tokenB);
}
if (pool == address(0)) {
pool = IDMMFactory(factory).createPool(tokenA, tokenB, ampBps);
}
// if we add liquidity to an existing pool, this is an unamplifed pool
// so there is no need for bounds of virtual reserve ratio
uint256[2] memory vReserveRatioBounds = [MIN_VRESERVE_RATIO, MAX_VRESERVE_RATIO];
(amountA, amountB, liquidity) = addLiquidity(
tokenA,
tokenB,
pool,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
vReserveRatioBounds,
to,
deadline
);
}
function addLiquidityNewPoolETH(
IERC20 token,
uint32 ampBps,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
override
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
)
{
address pool;
if (ampBps == BPS) {
pool = IDMMFactory(factory).getUnamplifiedPool(token, weth);
}
if (pool == address(0)) {
pool = IDMMFactory(factory).createPool(token, weth, ampBps);
}
// if we add liquidity to an existing pool, this is an unamplifed pool
// so there is no need for bounds of virtual reserve ratio
uint256[2] memory vReserveRatioBounds = [MIN_VRESERVE_RATIO, MAX_VRESERVE_RATIO];
(amountToken, amountETH, liquidity) = addLiquidityETH(
token,
pool,
amountTokenDesired,
amountTokenMin,
amountETHMin,
vReserveRatioBounds,
to,
deadline
);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) public override ensure(deadline) returns (uint256 amountA, uint256 amountB) {
verifyPoolAddress(tokenA, tokenB, pool);
IERC20(pool).safeTransferFrom(msg.sender, pool, liquidity); // send liquidity to pool
(uint256 amount0, uint256 amount1) = IDMMPool(pool).burn(to);
(IERC20 token0, ) = DMMLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, "DMMRouter: INSUFFICIENT_A_AMOUNT");
require(amountB >= amountBMin, "DMMRouter: INSUFFICIENT_B_AMOUNT");
}
function removeLiquidityETH(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) public override ensure(deadline) returns (uint256 amountToken, uint256 amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
weth,
pool,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
token.safeTransfer(to, amountToken);
IWETH(weth).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountA, uint256 amountB) {
uint256 value = approveMax ? uint256(-1) : liquidity;
IERC20Permit(pool).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(
tokenA,
tokenB,
pool,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
}
function removeLiquidityETHWithPermit(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external override returns (uint256 amountToken, uint256 amountETH) {
uint256 value = approveMax ? uint256(-1) : liquidity;
IERC20Permit(pool).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(
token,
pool,
liquidity,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) public override ensure(deadline) returns (uint256 amountETH) {
(, amountETH) = removeLiquidity(
token,
weth,
pool,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
token.safeTransfer(to, IERC20(token).balanceOf(address(this)));
IWETH(weth).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external override returns (uint256 amountETH) {
uint256 value = approveMax ? uint256(-1) : liquidity;
IERC20Permit(pool).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token,
pool,
liquidity,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pool
function _swap(
uint256[] memory amounts,
address[] memory poolsPath,
IERC20[] memory path,
address _to
) private {
for (uint256 i; i < path.length - 1; i++) {
(IERC20 input, IERC20 output) = (path[i], path[i + 1]);
(IERC20 token0, ) = DMMLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2 ? poolsPath[i + 1] : _to;
IDMMPool(poolsPath[i]).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] memory poolsPath,
IERC20[] memory path,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256[] memory amounts) {
verifyPoolsPathSwap(poolsPath, path);
amounts = DMMLibrary.getAmountsOut(amountIn, poolsPath, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"DMMRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
IERC20(path[0]).safeTransferFrom(msg.sender, poolsPath[0], amounts[0]);
_swap(amounts, poolsPath, path, to);
}
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] memory poolsPath,
IERC20[] memory path,
address to,
uint256 deadline
) public override ensure(deadline) returns (uint256[] memory amounts) {
verifyPoolsPathSwap(poolsPath, path);
amounts = DMMLibrary.getAmountsIn(amountOut, poolsPath, path);
require(amounts[0] <= amountInMax, "DMMRouter: EXCESSIVE_INPUT_AMOUNT");
path[0].safeTransferFrom(msg.sender, poolsPath[0], amounts[0]);
_swap(amounts, poolsPath, path, to);
}
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external override payable ensure(deadline) returns (uint256[] memory amounts) {
require(path[0] == weth, "DMMRouter: INVALID_PATH");
verifyPoolsPathSwap(poolsPath, path);
amounts = DMMLibrary.getAmountsOut(msg.value, poolsPath, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"DMMRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
IWETH(weth).deposit{value: amounts[0]}();
weth.safeTransfer(poolsPath[0], amounts[0]);
_swap(amounts, poolsPath, path, to);
}
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external override ensure(deadline) returns (uint256[] memory amounts) {
require(path[path.length - 1] == weth, "DMMRouter: INVALID_PATH");
verifyPoolsPathSwap(poolsPath, path);
amounts = DMMLibrary.getAmountsIn(amountOut, poolsPath, path);
require(amounts[0] <= amountInMax, "DMMRouter: EXCESSIVE_INPUT_AMOUNT");
path[0].safeTransferFrom(msg.sender, poolsPath[0], amounts[0]);
_swap(amounts, poolsPath, path, address(this));
IWETH(weth).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external override ensure(deadline) returns (uint256[] memory amounts) {
require(path[path.length - 1] == weth, "DMMRouter: INVALID_PATH");
verifyPoolsPathSwap(poolsPath, path);
amounts = DMMLibrary.getAmountsOut(amountIn, poolsPath, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"DMMRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
path[0].safeTransferFrom(msg.sender, poolsPath[0], amounts[0]);
_swap(amounts, poolsPath, path, address(this));
IWETH(weth).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external override payable ensure(deadline) returns (uint256[] memory amounts) {
require(path[0] == weth, "DMMRouter: INVALID_PATH");
verifyPoolsPathSwap(poolsPath, path);
amounts = DMMLibrary.getAmountsIn(amountOut, poolsPath, path);
require(amounts[0] <= msg.value, "DMMRouter: EXCESSIVE_INPUT_AMOUNT");
IWETH(weth).deposit{value: amounts[0]}();
weth.safeTransfer(poolsPath[0], amounts[0]);
_swap(amounts, poolsPath, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) {
TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pool
function _swapSupportingFeeOnTransferTokens(
address[] memory poolsPath,
IERC20[] memory path,
address _to
) internal {
verifyPoolsPathSwap(poolsPath, path);
for (uint256 i; i < path.length - 1; i++) {
(IERC20 input, IERC20 output) = (path[i], path[i + 1]);
(IERC20 token0, ) = DMMLibrary.sortTokens(input, output);
IDMMPool pool = IDMMPool(poolsPath[i]);
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(
uint256 reserveIn,
uint256 reserveOut,
uint256 vReserveIn,
uint256 vReserveOut,
uint256 feeInPrecision
) = DMMLibrary.getTradeInfo(poolsPath[i], input, output);
uint256 amountInput = IERC20(input).balanceOf(address(pool)).sub(reserveIn);
amountOutput = DMMLibrary.getAmountOut(
amountInput,
reserveIn,
reserveOut,
vReserveIn,
vReserveOut,
feeInPrecision
);
}
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to = i < path.length - 2 ? poolsPath[i + 1] : _to;
pool.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] memory poolsPath,
IERC20[] memory path,
address to,
uint256 deadline
) public override ensure(deadline) {
path[0].safeTransferFrom(msg.sender, poolsPath[0], amountIn);
uint256 balanceBefore = path[path.length - 1].balanceOf(to);
_swapSupportingFeeOnTransferTokens(poolsPath, path, to);
uint256 balanceAfter = path[path.length - 1].balanceOf(to);
require(
balanceAfter >= balanceBefore.add(amountOutMin),
"DMMRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external override payable ensure(deadline) {
require(path[0] == weth, "DMMRouter: INVALID_PATH");
uint256 amountIn = msg.value;
IWETH(weth).deposit{value: amountIn}();
weth.safeTransfer(poolsPath[0], amountIn);
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(poolsPath, path, to);
require(
path[path.length - 1].balanceOf(to).sub(balanceBefore) >= amountOutMin,
"DMMRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata poolsPath,
IERC20[] calldata path,
address to,
uint256 deadline
) external override ensure(deadline) {
require(path[path.length - 1] == weth, "DMMRouter: INVALID_PATH");
path[0].safeTransferFrom(msg.sender, poolsPath[0], amountIn);
_swapSupportingFeeOnTransferTokens(poolsPath, path, address(this));
uint256 amountOut = IWETH(weth).balanceOf(address(this));
require(amountOut >= amountOutMin, "DMMRouter: INSUFFICIENT_OUTPUT_AMOUNT");
IWETH(weth).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
/// @dev get the amount of tokenB for adding liquidity with given amount of token A and the amount of tokens in the pool
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external override pure returns (uint256 amountB) {
return DMMLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountsOut(
uint256 amountIn,
address[] calldata poolsPath,
IERC20[] calldata path
) external override view returns (uint256[] memory amounts) {
verifyPoolsPathSwap(poolsPath, path);
return DMMLibrary.getAmountsOut(amountIn, poolsPath, path);
}
function getAmountsIn(
uint256 amountOut,
address[] calldata poolsPath,
IERC20[] calldata path
) external override view returns (uint256[] memory amounts) {
verifyPoolsPathSwap(poolsPath, path);
return DMMLibrary.getAmountsIn(amountOut, poolsPath, path);
}
function verifyPoolsPathSwap(address[] memory poolsPath, IERC20[] memory path) internal view {
require(path.length >= 2, "DMMRouter: INVALID_PATH");
require(poolsPath.length == path.length - 1, "DMMRouter: INVALID_POOLS_PATH");
for (uint256 i = 0; i < poolsPath.length; i++) {
verifyPoolAddress(path[i], path[i + 1], poolsPath[i]);
}
}
function verifyPoolAddress(
IERC20 tokenA,
IERC20 tokenB,
address pool
) internal view {
require(IDMMFactory(factory).isPool(tokenA, tokenB, pool), "DMMRouter: INVALID_POOL");
}
} | using tokenA.safeTransferFrom will get "Stack too deep" | function addLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
uint256[2] memory vReserveRatioBounds,
address to,
uint256 deadline
)
public
virtual
override
ensure(deadline)
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
verifyPoolAddress(tokenA, tokenB, pool);
(amountA, amountB) = _addLiquidity(
tokenA,
tokenB,
pool,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
vReserveRatioBounds
);
SafeERC20.safeTransferFrom(tokenA, msg.sender, pool, amountA);
SafeERC20.safeTransferFrom(tokenB, msg.sender, pool, amountB);
liquidity = IDMMPool(pool).mint(to);
}
| 2,503,169 | [
1,
9940,
1147,
37,
18,
4626,
5912,
1265,
903,
336,
315,
2624,
4885,
4608,
6,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
48,
18988,
24237,
12,
203,
3639,
467,
654,
39,
3462,
1147,
37,
16,
203,
3639,
467,
654,
39,
3462,
1147,
38,
16,
203,
3639,
1758,
2845,
16,
203,
3639,
2254,
5034,
3844,
1880,
281,
2921,
16,
203,
3639,
2254,
5034,
3844,
38,
25683,
16,
203,
3639,
2254,
5034,
3844,
2192,
267,
16,
203,
3639,
2254,
5034,
3844,
38,
2930,
16,
203,
3639,
2254,
5034,
63,
22,
65,
3778,
331,
607,
6527,
8541,
5694,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
14096,
203,
565,
262,
203,
3639,
1071,
203,
3639,
5024,
203,
3639,
3849,
203,
3639,
3387,
12,
22097,
1369,
13,
203,
3639,
1135,
261,
203,
5411,
2254,
5034,
3844,
37,
16,
203,
5411,
2254,
5034,
3844,
38,
16,
203,
5411,
2254,
5034,
4501,
372,
24237,
203,
3639,
262,
203,
565,
288,
203,
3639,
3929,
2864,
1887,
12,
2316,
37,
16,
1147,
38,
16,
2845,
1769,
203,
3639,
261,
8949,
37,
16,
3844,
38,
13,
273,
389,
1289,
48,
18988,
24237,
12,
203,
5411,
1147,
37,
16,
203,
5411,
1147,
38,
16,
203,
5411,
2845,
16,
203,
5411,
3844,
1880,
281,
2921,
16,
203,
5411,
3844,
38,
25683,
16,
203,
5411,
3844,
2192,
267,
16,
203,
5411,
3844,
38,
2930,
16,
203,
5411,
331,
607,
6527,
8541,
5694,
203,
3639,
11272,
203,
3639,
14060,
654,
39,
3462,
18,
4626,
5912,
1265,
12,
2316,
37,
16,
1234,
18,
15330,
16,
2845,
16,
3844,
37,
1769,
203,
3639,
14060,
654,
39,
3462,
18,
4626,
5912,
1265,
12,
2316,
38,
16,
1234,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/IYieldGenerator.sol";
import "./interfaces/IDefiProtocol.sol";
import "./interfaces/ICapitalPool.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract YieldGenerator is IYieldGenerator, OwnableUpgradeable, AbstractDependant {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using Math for uint256;
uint256 public constant DEPOSIT_SAFETY_MARGIN = 15 * 10**24; //1.5
uint256 public constant PROTOCOLS_NUMBER = 3;
ERC20 public stblToken;
ICapitalPool public capitalPool;
uint256 public totalDeposit;
uint256 public whitelistedProtocols;
// index => defi protocol
mapping(uint256 => DefiProtocol) internal defiProtocols;
// index => defi protocol addresses
mapping(uint256 => address) public defiProtocolsAddresses;
// available protcols to deposit/withdraw (weighted and threshold is true)
uint256[] internal availableProtocols;
// selected protocols for multiple deposit/withdraw
uint256[] internal _selectedProtocols;
event DefiDeposited(
uint256 indexed protocolIndex,
uint256 amount,
uint256 depositedPercentage
);
event DefiWithdrawn(uint256 indexed protocolIndex, uint256 amount, uint256 withdrawPercentage);
modifier onlyCapitalPool() {
require(_msgSender() == address(capitalPool), "YG: Not a capital pool contract");
_;
}
modifier updateDefiProtocols(uint256 amount, bool isDeposit) {
_updateDefiProtocols(amount, isDeposit);
_;
}
function __YieldGenerator_init() external initializer {
__Ownable_init();
whitelistedProtocols = 3;
// setup AAVE
defiProtocols[uint256(DefiProtocols.AAVE)].targetAllocation = 45 * PRECISION;
defiProtocols[uint256(DefiProtocols.AAVE)].whiteListed = true;
defiProtocols[uint256(DefiProtocols.AAVE)].threshold = true;
// setup Compound
defiProtocols[uint256(DefiProtocols.COMPOUND)].targetAllocation = 45 * PRECISION;
defiProtocols[uint256(DefiProtocols.COMPOUND)].whiteListed = true;
defiProtocols[uint256(DefiProtocols.COMPOUND)].threshold = true;
// setup Yearn
defiProtocols[uint256(DefiProtocols.YEARN)].targetAllocation = 10 * PRECISION;
defiProtocols[uint256(DefiProtocols.YEARN)].whiteListed = true;
defiProtocols[uint256(DefiProtocols.YEARN)].threshold = true;
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
stblToken = ERC20(_contractsRegistry.getUSDTContract());
capitalPool = ICapitalPool(_contractsRegistry.getCapitalPoolContract());
defiProtocolsAddresses[uint256(DefiProtocols.AAVE)] = _contractsRegistry
.getAaveProtocolContract();
defiProtocolsAddresses[uint256(DefiProtocols.COMPOUND)] = _contractsRegistry
.getCompoundProtocolContract();
defiProtocolsAddresses[uint256(DefiProtocols.YEARN)] = _contractsRegistry
.getYearnProtocolContract();
}
/// @notice deposit stable coin into multiple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to deposit
function deposit(uint256 amount) external override onlyCapitalPool returns (uint256) {
if (amount == 0 && _getCurrentvSTBLVolume() == 0) return 0;
return _aggregateDepositWithdrawFunction(amount, true);
}
/// @notice withdraw stable coin from mulitple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to withdraw
function withdraw(uint256 amount) external override onlyCapitalPool returns (uint256) {
if (amount == 0 && _getCurrentvSTBLVolume() == 0) return 0;
return _aggregateDepositWithdrawFunction(amount, false);
}
/// @notice set the protocol settings for each defi protocol (allocations, whitelisted, depositCost), access: owner
/// @param whitelisted bool[] list of whitelisted values for each protocol
/// @param allocations uint256[] list of allocations value for each protocol
/// @param depositCost uint256[] list of depositCost values for each protocol
function setProtocolSettings(
bool[] calldata whitelisted,
uint256[] calldata allocations,
uint256[] calldata depositCost
) external override onlyOwner {
require(
whitelisted.length == PROTOCOLS_NUMBER &&
allocations.length == PROTOCOLS_NUMBER &&
depositCost.length == PROTOCOLS_NUMBER,
"YG: Invlaid arr length"
);
whitelistedProtocols = 0;
bool _whiteListed;
for (uint256 i = 0; i < PROTOCOLS_NUMBER; i++) {
_whiteListed = whitelisted[i];
if (_whiteListed) {
whitelistedProtocols = whitelistedProtocols.add(1);
}
defiProtocols[i].targetAllocation = allocations[i];
defiProtocols[i].whiteListed = _whiteListed;
defiProtocols[i].depositCost = depositCost[i];
}
}
/// @notice claim rewards for all defi protocols and send them to reinsurance pool, access: owner
function claimRewards() external override onlyOwner {
for (uint256 i = 0; i < PROTOCOLS_NUMBER; i++) {
IDefiProtocol(defiProtocolsAddresses[i]).claimRewards();
}
}
/// @notice returns defi protocol APR by its index
/// @param index uint256 the index of the defi protocol
function getOneDayGain(uint256 index) public view returns (uint256) {
return IDefiProtocol(defiProtocolsAddresses[index]).getOneDayGain();
}
/// @notice returns defi protocol info by its index
/// @param index uint256 the index of the defi protocol
function defiProtocol(uint256 index)
external
view
override
returns (
uint256 _targetAllocation,
uint256 _currentAllocation,
uint256 _rebalanceWeight,
uint256 _depositedAmount,
bool _whiteListed,
bool _threshold,
uint256 _totalValue,
uint256 _depositCost
)
{
_targetAllocation = defiProtocols[index].targetAllocation;
_currentAllocation = _calcProtocolCurrentAllocation(index);
_rebalanceWeight = defiProtocols[index].rebalanceWeight;
_depositedAmount = defiProtocols[index].depositedAmount;
_whiteListed = defiProtocols[index].whiteListed;
_threshold = defiProtocols[index].threshold;
_totalValue = IDefiProtocol(defiProtocolsAddresses[index]).totalValue();
_depositCost = defiProtocols[index].depositCost;
}
function _aggregateDepositWithdrawFunction(uint256 amount, bool isDeposit)
internal
updateDefiProtocols(amount, isDeposit)
returns (uint256 _actualAmount)
{
if (availableProtocols.length == 0) {
return _actualAmount;
}
uint256 _protocolsNo = _howManyProtocols(amount, isDeposit);
if (_protocolsNo == 1) {
_actualAmount = _aggregateDepositWithdrawFunctionForOneProtocol(amount, isDeposit);
} else if (_protocolsNo > 1) {
delete _selectedProtocols;
uint256 _totalWeight = _calcTotalWeight(_protocolsNo, isDeposit);
if (_selectedProtocols.length > 0) {
for (uint256 i = 0; i < _selectedProtocols.length; i++) {
_actualAmount = _actualAmount.add(
_aggregateDepositWithdrawFunctionForMultipleProtocol(
isDeposit,
amount,
i,
_totalWeight
)
);
}
}
}
}
function _aggregateDepositWithdrawFunctionForOneProtocol(uint256 amount, bool isDeposit)
internal
returns (uint256 _actualAmount)
{
uint256 _protocolIndex;
if (isDeposit) {
_protocolIndex = _getProtocolOfMaxWeight();
// deposit 100% to this protocol
_depoist(_protocolIndex, amount, PERCENTAGE_100);
_actualAmount = amount;
} else {
_protocolIndex = _getProtocolOfMinWeight();
// withdraw 100% from this protocol
_actualAmount = _withdraw(_protocolIndex, amount, PERCENTAGE_100);
}
}
function _aggregateDepositWithdrawFunctionForMultipleProtocol(
bool isDeposit,
uint256 amount,
uint256 index,
uint256 _totalWeight
) internal returns (uint256 _actualAmount) {
uint256 _protocolRebalanceAllocation =
_calcRebalanceAllocation(_selectedProtocols[index], _totalWeight);
if (isDeposit) {
// deposit % allocation to this protocol
uint256 _depoistedAmount =
amount.mul(_protocolRebalanceAllocation).div(PERCENTAGE_100);
_depoist(_selectedProtocols[index], _depoistedAmount, _protocolRebalanceAllocation);
_actualAmount = _depoistedAmount;
} else {
_actualAmount = _withdraw(
_selectedProtocols[index],
amount.mul(_protocolRebalanceAllocation).div(PERCENTAGE_100),
_protocolRebalanceAllocation
);
}
}
function _calcTotalWeight(uint256 _protocolsNo, bool isDeposit)
internal
returns (uint256 _totalWeight)
{
uint256 _protocolIndex;
for (uint256 i = 0; i < _protocolsNo; i++) {
if (availableProtocols.length == 0) {
break;
}
if (isDeposit) {
_protocolIndex = _getProtocolOfMaxWeight();
} else {
_protocolIndex = _getProtocolOfMinWeight();
}
_totalWeight = _totalWeight.add(defiProtocols[_protocolIndex].rebalanceWeight);
_selectedProtocols.push(_protocolIndex);
}
}
/// @notice deposit into defi protocols
/// @param _protocolIndex uint256 the predefined index of the defi protocol
/// @param _amount uint256 amount of stable coin to deposit
/// @param _depositedPercentage uint256 the percentage of deposited amount into the protocol
function _depoist(
uint256 _protocolIndex,
uint256 _amount,
uint256 _depositedPercentage
) internal {
// should approve yield to transfer from the capital pool
stblToken.safeTransferFrom(_msgSender(), defiProtocolsAddresses[_protocolIndex], _amount);
IDefiProtocol(defiProtocolsAddresses[_protocolIndex]).deposit(_amount);
defiProtocols[_protocolIndex].depositedAmount = defiProtocols[_protocolIndex]
.depositedAmount
.add(_amount);
totalDeposit = totalDeposit.add(_amount);
emit DefiDeposited(_protocolIndex, _amount, _depositedPercentage);
}
/// @notice withdraw from defi protocols
/// @param _protocolIndex uint256 the predefined index of the defi protocol
/// @param _amount uint256 amount of stable coin to withdraw
/// @param _withdrawnPercentage uint256 the percentage of withdrawn amount from the protocol
function _withdraw(
uint256 _protocolIndex,
uint256 _amount,
uint256 _withdrawnPercentage
) internal returns (uint256) {
uint256 _actualAmountWithdrawn;
uint256 allocatedFunds = defiProtocols[_protocolIndex].depositedAmount;
if (allocatedFunds == 0) return _actualAmountWithdrawn;
if (allocatedFunds < _amount) {
_amount = allocatedFunds;
}
_actualAmountWithdrawn = IDefiProtocol(defiProtocolsAddresses[_protocolIndex]).withdraw(
_amount
);
defiProtocols[_protocolIndex].depositedAmount = defiProtocols[_protocolIndex]
.depositedAmount
.sub(_actualAmountWithdrawn);
totalDeposit = totalDeposit.sub(_actualAmountWithdrawn);
emit DefiWithdrawn(_protocolIndex, _actualAmountWithdrawn, _withdrawnPercentage);
return _actualAmountWithdrawn;
}
/// @notice get the number of protocols need to rebalance
/// @param rebalanceAmount uint256 the amount of stable coin will depsoit or withdraw
function _howManyProtocols(uint256 rebalanceAmount, bool isDeposit)
internal
view
returns (uint256)
{
uint256 _no1;
if (isDeposit) {
_no1 = whitelistedProtocols.mul(rebalanceAmount);
} else {
_no1 = PROTOCOLS_NUMBER.mul(rebalanceAmount);
}
uint256 _no2 = _getCurrentvSTBLVolume();
return _no1.add(_no2 - 1).div(_no2);
//return _no1.div(_no2).add(_no1.mod(_no2) == 0 ? 0 : 1);
}
/// @notice update defi protocols rebalance weight and threshold status
/// @param isDeposit bool determine the rebalance is for deposit or withdraw
function _updateDefiProtocols(uint256 amount, bool isDeposit) internal {
delete availableProtocols;
for (uint256 i = 0; i < PROTOCOLS_NUMBER; i++) {
uint256 _targetAllocation = defiProtocols[i].targetAllocation;
uint256 _currentAllocation = _calcProtocolCurrentAllocation(i);
uint256 _diffAllocation;
if (isDeposit) {
if (_targetAllocation > _currentAllocation) {
// max weight
_diffAllocation = _targetAllocation.sub(_currentAllocation);
} else if (_currentAllocation >= _targetAllocation) {
_diffAllocation = 0;
}
_reevaluateThreshold(i, _diffAllocation.mul(amount).div(PERCENTAGE_100));
} else {
if (_currentAllocation > _targetAllocation) {
// max weight
_diffAllocation = _currentAllocation.sub(_targetAllocation);
defiProtocols[i].withdrawMax = true;
} else if (_targetAllocation >= _currentAllocation) {
// min weight
_diffAllocation = _targetAllocation.sub(_currentAllocation);
defiProtocols[i].withdrawMax = false;
}
}
// update rebalance weight
defiProtocols[i].rebalanceWeight = _diffAllocation.mul(_getCurrentvSTBLVolume()).div(
PERCENTAGE_100
);
if (
isDeposit
? defiProtocols[i].rebalanceWeight > 0 &&
defiProtocols[i].whiteListed &&
defiProtocols[i].threshold
: _currentAllocation > 0
) {
availableProtocols.push(i);
}
}
}
/// @notice get the defi protocol has max weight to deposit
/// @dev only select the positive weight from largest to smallest
function _getProtocolOfMaxWeight() internal returns (uint256) {
uint256 _largest;
uint256 _protocolIndex;
uint256 _indexToDelete;
for (uint256 i = 0; i < availableProtocols.length; i++) {
if (defiProtocols[availableProtocols[i]].rebalanceWeight > _largest) {
_largest = defiProtocols[availableProtocols[i]].rebalanceWeight;
_protocolIndex = availableProtocols[i];
_indexToDelete = i;
}
}
availableProtocols[_indexToDelete] = availableProtocols[availableProtocols.length - 1];
availableProtocols.pop();
return _protocolIndex;
}
/// @notice get the defi protocol has min weight to deposit
/// @dev only select the negative weight from smallest to largest
function _getProtocolOfMinWeight() internal returns (uint256) {
uint256 _maxWeight;
for (uint256 i = 0; i < availableProtocols.length; i++) {
if (defiProtocols[availableProtocols[i]].rebalanceWeight > _maxWeight) {
_maxWeight = defiProtocols[availableProtocols[i]].rebalanceWeight;
}
}
uint256 _smallest = _maxWeight;
uint256 _largest;
uint256 _maxProtocolIndex;
uint256 _maxIndexToDelete;
uint256 _minProtocolIndex;
uint256 _minIndexToDelete;
for (uint256 i = 0; i < availableProtocols.length; i++) {
if (
defiProtocols[availableProtocols[i]].rebalanceWeight <= _smallest &&
!defiProtocols[availableProtocols[i]].withdrawMax
) {
_smallest = defiProtocols[availableProtocols[i]].rebalanceWeight;
_minProtocolIndex = availableProtocols[i];
_minIndexToDelete = i;
} else if (
defiProtocols[availableProtocols[i]].rebalanceWeight > _largest &&
defiProtocols[availableProtocols[i]].withdrawMax
) {
_largest = defiProtocols[availableProtocols[i]].rebalanceWeight;
_maxProtocolIndex = availableProtocols[i];
_maxIndexToDelete = i;
}
}
if (_largest > 0) {
availableProtocols[_maxIndexToDelete] = availableProtocols[
availableProtocols.length - 1
];
availableProtocols.pop();
return _maxProtocolIndex;
} else {
availableProtocols[_minIndexToDelete] = availableProtocols[
availableProtocols.length - 1
];
availableProtocols.pop();
return _minProtocolIndex;
}
}
/// @notice calc the current allocation of defi protocol against current vstable volume
/// @param _protocolIndex uint256 the predefined index of defi protocol
function _calcProtocolCurrentAllocation(uint256 _protocolIndex)
internal
view
returns (uint256 _currentAllocation)
{
uint256 _depositedAmount = defiProtocols[_protocolIndex].depositedAmount;
uint256 _currentvSTBLVolume = _getCurrentvSTBLVolume();
if (_currentvSTBLVolume > 0) {
_currentAllocation = _depositedAmount.mul(PERCENTAGE_100).div(_currentvSTBLVolume);
}
}
/// @notice calc the rebelance allocation % for one protocol for deposit/withdraw
/// @param _protocolIndex uint256 the predefined index of defi protocol
/// @param _totalWeight uint256 sum of rebelance weight for all protocols which avaiable for deposit/withdraw
function _calcRebalanceAllocation(uint256 _protocolIndex, uint256 _totalWeight)
internal
view
returns (uint256)
{
return defiProtocols[_protocolIndex].rebalanceWeight.mul(PERCENTAGE_100).div(_totalWeight);
}
function _getCurrentvSTBLVolume() internal view returns (uint256) {
return
capitalPool.virtualUsdtAccumulatedBalance().sub(capitalPool.liquidityCushionBalance());
}
function _reevaluateThreshold(uint256 _protocolIndex, uint256 depositAmount) internal {
uint256 _protocolOneDayGain = getOneDayGain(_protocolIndex);
uint256 _oneDayReturn = _protocolOneDayGain.mul(depositAmount).div(PRECISION);
uint256 _depositCost = defiProtocols[_protocolIndex].depositCost;
if (_oneDayReturn < _depositCost) {
defiProtocols[_protocolIndex].threshold = false;
} else if (_oneDayReturn >= _depositCost) {
defiProtocols[_protocolIndex].threshold = true;
}
}
function reevaluateDefiProtocolBalances()
external
override
returns (uint256 _totalDeposit, uint256 _lostAmount)
{
_totalDeposit = totalDeposit;
uint256 _totalValue;
uint256 _depositedAmount;
for (uint256 index = 0; index < PROTOCOLS_NUMBER; index++) {
if (index == uint256(DefiProtocols.COMPOUND)) {
IDefiProtocol(defiProtocolsAddresses[index]).updateTotalValue();
}
_totalValue = IDefiProtocol(defiProtocolsAddresses[index]).totalValue();
_depositedAmount = defiProtocols[index].depositedAmount;
if (_totalValue < _depositedAmount) {
_lostAmount = _lostAmount.add((_depositedAmount.sub(_totalValue)));
}
}
}
function defiHardRebalancing() external override onlyCapitalPool {
uint256 _totalValue;
uint256 _depositedAmount;
uint256 _lostAmount;
uint256 _totalLostAmount;
for (uint256 index = 0; index < PROTOCOLS_NUMBER; index++) {
_totalValue = IDefiProtocol(defiProtocolsAddresses[index]).totalValue();
_depositedAmount = defiProtocols[index].depositedAmount;
if (_totalValue < _depositedAmount) {
_lostAmount = _depositedAmount.sub(_totalValue);
defiProtocols[index].depositedAmount = _depositedAmount.sub(_lostAmount);
IDefiProtocol(defiProtocolsAddresses[index]).updateTotalDeposit(_lostAmount);
_totalLostAmount = _totalLostAmount.add(_lostAmount);
}
}
totalDeposit = totalDeposit.sub(_lostAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFacade.sol";
interface ICapitalPool {
struct PremiumFactors {
uint256 epochsNumber;
uint256 premiumPrice;
uint256 vStblDeployedByRP;
uint256 vStblOfCP;
uint256 poolUtilizationRation;
uint256 premiumPerDeployment;
uint256 userLeveragePoolsCount;
IPolicyBookFacade policyBookFacade;
}
enum PoolType {COVERAGE, LEVERAGE, REINSURANCE}
function virtualUsdtAccumulatedBalance() external view returns (uint256);
function liquidityCushionBalance() external view returns (uint256);
/// @notice distributes the policybook premiums into pools (CP, ULP , RP)
/// @dev distributes the balances acording to the established percentages
/// @param _stblAmount amount hardSTBL ingressed into the system
/// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param _protocolFee uint256 the amount of protocol fee earned by premium
function addPolicyHoldersHardSTBL(
uint256 _stblAmount,
uint256 _epochsNumber,
uint256 _protocolFee
) external returns (uint256);
/// @notice distributes the hardSTBL from the coverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addCoverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the leverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addLeverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the reinsurance pool
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addReinsurancePoolHardSTBL(uint256 _stblAmount) external;
/// @notice rebalances pools acording to v2 specification and dao enforced policies
/// @dev emits PoolBalancesUpdated
function rebalanceLiquidityCushion() external;
/// @notice Fullfils policybook claims by transfering the balance to claimer
/// @param _claimer, address of the claimer recieving the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
function fundClaim(address _claimer, uint256 _stblAmount) external;
/// @notice Withdraws liquidity from a specific policbybook to the user
/// @param _sender, address of the user beneficiary of the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
/// @param _isLeveragePool bool wether the pool is ULP or CP(policybook)
function withdrawLiquidity(
address _sender,
uint256 _stblAmount,
bool _isLeveragePool
) external;
function rebalanceDuration() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IClaimingRegistry {
enum ClaimStatus {
CAN_CLAIM,
UNCLAIMABLE,
PENDING,
AWAITING_CALCULATION,
REJECTED_CAN_APPEAL,
REJECTED,
ACCEPTED
}
struct ClaimInfo {
address claimer;
address policyBookAddress;
string evidenceURI;
uint256 dateSubmitted;
uint256 dateEnded;
bool appeal;
ClaimStatus status;
uint256 claimAmount;
}
/// @notice returns anonymous voting duration
function anonymousVotingDuration(uint256 index) external view returns (uint256);
/// @notice returns the whole voting duration
function votingDuration(uint256 index) external view returns (uint256);
/// @notice returns how many time should pass before anyone could calculate a claim result
function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256);
/// @notice returns true if a user can buy new policy of specified PolicyBook
function canBuyNewPolicy(address buyer, address policyBookAddress)
external
view
returns (bool);
/// @notice submits new PolicyBook claim for the user
function submitClaim(
address user,
address policyBookAddress,
string calldata evidenceURI,
uint256 cover,
bool appeal
) external returns (uint256);
/// @notice returns true if the claim with this index exists
function claimExists(uint256 index) external view returns (bool);
/// @notice returns claim submition time
function claimSubmittedTime(uint256 index) external view returns (uint256);
/// @notice returns claim end time or zero in case it is pending
function claimEndTime(uint256 index) external view returns (uint256);
/// @notice returns true if the claim is anonymously votable
function isClaimAnonymouslyVotable(uint256 index) external view returns (bool);
/// @notice returns true if the claim is exposably votable
function isClaimExposablyVotable(uint256 index) external view returns (bool);
/// @notice returns true if claim is anonymously votable or exposably votable
function isClaimVotable(uint256 index) external view returns (bool);
/// @notice returns true if a claim can be calculated by anyone
function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool);
/// @notice returns true if this claim is pending or awaiting
function isClaimPending(uint256 index) external view returns (bool);
/// @notice returns how many claims the holder has
function countPolicyClaimerClaims(address user) external view returns (uint256);
/// @notice returns how many pending claims are there
function countPendingClaims() external view returns (uint256);
/// @notice returns how many claims are there
function countClaims() external view returns (uint256);
/// @notice returns a claim index of it's claimer and an ordinal number
function claimOfOwnerIndexAt(address claimer, uint256 orderIndex)
external
view
returns (uint256);
/// @notice returns pending claim index by its ordinal index
function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns claim index by its ordinal index
function claimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns current active claim index by policybook and claimer
function claimIndex(address claimer, address policyBookAddress)
external
view
returns (uint256);
/// @notice returns true if the claim is appealed
function isClaimAppeal(uint256 index) external view returns (bool);
/// @notice returns current status of a claim
function policyStatus(address claimer, address policyBookAddress)
external
view
returns (ClaimStatus);
/// @notice returns current status of a claim
function claimStatus(uint256 index) external view returns (ClaimStatus);
/// @notice returns the claim owner (claimer)
function claimOwner(uint256 index) external view returns (address);
/// @notice returns the claim PolicyBook
function claimPolicyBook(uint256 index) external view returns (address);
/// @notice returns claim info by its index
function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo);
function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount);
function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256);
/// @notice marks the user's claim as Accepted
function acceptClaim(uint256 index) external;
/// @notice marks the user's claim as Rejected
function rejectClaim(uint256 index) external;
/// @notice Update Image Uri in case it contains material that is ilegal
/// or offensive.
/// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri.
/// @param _claimIndex Claim Index that is going to be updated
/// @param _newEvidenceURI New evidence uri. It can be blank.
function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityBridgeContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @notice Interface for defi protocols (Compound, Aave, bZx, etc.)
interface IDefiProtocol {
/// @return uint256 The total value locked in the defi protocol, in terms of the underlying stablecoin
function totalValue() external view returns (uint256);
/// @return ERC20 the erc20 stable coin which depoisted in the defi protocol
function stablecoin() external view returns (ERC20);
/// @notice deposit an amount in defi protocol
/// @param amount uint256 the amount of stable coin will deposit
function deposit(uint256 amount) external;
/// @notice withdraw an amount from defi protocol
/// @param amountInUnderlying uint256 the amount of underlying token to withdraw the deposited stable coin
function withdraw(uint256 amountInUnderlying) external returns (uint256 actualAmountWithdrawn);
/// @notice Claims farmed tokens and sends it to the rewards pool
function claimRewards() external;
/// @notice set the address of receiving rewards
/// @param newValue address the new address to recieve the rewards
function setRewards(address newValue) external;
/// @notice get protocol gain for one day for one unit
function getOneDayGain() external view returns (uint256);
///@dev update total value only for compound
function updateTotalValue() external returns (uint256);
///@dev update total deposit in case of hard rebalancing
function updateTotalDeposit(uint256 _lostAmount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface ILeveragePortfolio {
enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL}
struct LevFundsFactors {
uint256 netMPL;
uint256 netMPLn;
address policyBookAddr;
}
function targetUR() external view returns (uint256);
function d_ProtocolConstant() external view returns (uint256);
function a_ProtocolConstant() external view returns (uint256);
function max_ProtocolConstant() external view returns (uint256);
/// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook.
/// @param leveragePoolType LeveragePortfolio is determine the pool which call the function
function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType)
external
returns (uint256);
/// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook.
function deployVirtualStableToCoveragePools() external returns (uint256);
/// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner
/// @param threshold uint256 is the reevaluatation threshold
function setRebalancingThreshold(uint256 threshold) external;
/// @notice set the protocol constant : access by owner
/// @param _targetUR uint256 target utitlization ration
/// @param _d_ProtocolConstant uint256 D protocol constant
/// @param _a1_ProtocolConstant uint256 A1 protocol constant
/// @param _max_ProtocolConstant uint256 the max % included
function setProtocolConstant(
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a1_ProtocolConstant,
uint256 _max_ProtocolConstant
) external;
/// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max)
/// @param poolUR uint256 utitilization ratio for a coverage pool
/// @return uint256 M facotr
//function calcM(uint256 poolUR) external returns (uint256);
/// @return uint256 the amount of vStable stored in the pool
function totalLiquidity() external view returns (uint256);
/// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook
/// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook
/// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium
function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external;
/// @notice Used to get a list of coverage pools which get leveraged , use with count()
/// @return _coveragePools a list containing policybook addresses
function listleveragedCoveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _coveragePools);
/// @notice get count of coverage pools which get leveraged
function countleveragedCoveragePools() external view returns (uint256);
function updateLiquidity(uint256 _lostLiquidity) external;
function forceUpdateBMICoverStakingRewardMultiplier() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IPolicyBook {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct PolicyHolder {
uint256 coverTokens;
uint256 startEpochNumber;
uint256 endEpochNumber;
uint256 paid;
uint256 reinsurancePrice;
}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BuyPolicyParameters {
address buyer;
address holder;
uint256 epochsNumber;
uint256 coverTokens;
uint256 distributorFee;
address distributor;
}
function policyHolders(address _holder)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function policyBookFacade() external view returns (IPolicyBookFacade);
function setPolicyBookFacade(address _policyBookFacade) external;
function EPOCH_DURATION() external view returns (uint256);
function stblDecimals() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function whitelisted() external view returns (bool);
function epochStartTime() external view returns (uint256);
// @TODO: should we let DAO to change contract address?
/// @notice Returns address of contract this PolicyBook covers, access: ANY
/// @return _contract is address of covered contract
function insuranceContractAddress() external view returns (address _contract);
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function totalLiquidity() external view returns (uint256);
function totalCoverTokens() external view returns (uint256);
// /// @notice return MPL for user leverage pool
// function userleveragedMPL() external view returns (uint256);
// /// @notice return MPL for reinsurance pool
// function reinsurancePoolMPL() external view returns (uint256);
// function bmiRewardMultiplier() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __PolicyBook_init(
address _insuranceContract,
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function whitelist(bool _whitelisted) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice submits new claim of the policy book
function submitClaimAndInitializeVoting(string calldata evidenceURI) external;
/// @notice submits new appeal claim of the policy book
function submitAppealAndInitializeVoting(string calldata evidenceURI) external;
/// @notice updates info on claim acceptance
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external;
/// @notice forces an update of RewardsGenerator multiplier
function forceUpdateBMICoverStakingRewardMultiplier() external;
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
/// @notice view function to get precise policy price
/// @param _epochsNumber is number of epochs to cover
/// @param _coverTokens is number of tokens to cover
/// @param _buyer address of the user who buy the policy
/// @return totalSeconds is number of seconds to cover
/// @return totalPrice is the policy price which will pay by the buyer
function getPolicyPrice(
uint256 _epochsNumber,
uint256 _coverTokens,
address _buyer
)
external
view
returns (
uint256 totalSeconds,
uint256 totalPrice,
uint256 pricePercentage
);
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _buyer who is transferring funds
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicy(
address _buyer,
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) external returns (uint256, uint256);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
/// @param _liquidityHolderAddr is address of address to assign cover
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityBuyerAddr address the one that transfer funds
/// @param _liquidityHolderAddr address the one that owns liquidity
/// @param _liquidityAmount uint256 amount to be added on behalf the sender
/// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake
function addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external returns (uint256);
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity(address sender) external returns (uint256);
///@notice for doing defi hard rebalancing, access: policyBookFacade
function updateLiquidity(uint256 _newLiquidity) external;
function getAPY() external view returns (uint256);
/// @notice Getting user stats, access: ANY
function userStats(address _user) external view returns (PolicyHolder memory);
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max token amount that a user can buy
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is a type of insured contract
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit,
address _shieldMiningToken
) external returns (address);
function createLeveragePools(
address _insuranceContract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./IPolicyBook.sol";
import "./ILeveragePortfolio.sol";
interface IPolicyBookFacade {
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external;
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicyFor(
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens
) external;
function policyBook() external view returns (IPolicyBook);
function userLiquidity(address account) external view returns (uint256);
/// @notice virtual funds deployed by reinsurance pool
function VUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by reinsurance pool
function LUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by user leverage pool
function LUuserLeveragePool(address userLeveragePool) external view returns (uint256);
/// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool)
function totalLeveragedLiquidity() external view returns (uint256);
function userleveragedMPL() external view returns (uint256);
function reinsurancePoolMPL() external view returns (uint256);
function rebalancingThreshold() external view returns (uint256);
function safePricingModel() external view returns (bool);
/// @notice policyBookFacade initializer
/// @param pbProxy polciybook address upgreadable cotnract.
function __PolicyBookFacade_init(
address pbProxy,
address liquidityProvider,
uint256 initialDeposit
) external;
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributor(
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @param _buyer who is buying the coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributorFor(
address _buyer,
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _user the one taht add liquidity
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external;
function addLiquidityAndStakeFor(
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external;
/// @notice Let user to add liquidity by supplying stable coin and stake it,
/// @dev access: ANY
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
/// @notice deploy leverage funds (RP lStable, ULP lStable)
/// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity
/// @param leveragePool whether user leverage or reinsurance leverage
function deployLeverageFundsAfterRebalance(
uint256 deployedAmount,
ILeveragePortfolio.LeveragePortfolio leveragePool
) external;
/// @notice deploy virtual funds (RP vStable)
/// @param deployedAmount uint256 the deployed amount to be added to the liquidity
function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external;
///@dev in case ur changed of the pools by commit a claim or policy expired
function reevaluateProvidedLeverageStable() external;
/// @notice set the MPL for the user leverage and the reinsurance leverage
/// @param _userLeverageMPL uint256 value of the user leverage MPL
/// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL
function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external;
/// @notice sets the rebalancing threshold value
/// @param _newRebalancingThreshold uint256 rebalancing threshhold value
function setRebalancingThreshold(uint256 _newRebalancingThreshold) external;
/// @notice sets the rebalancing threshold value
/// @param _safePricingModel bool is pricing model safe (true) or not (false)
function setSafePricingModel(bool _safePricingModel) external;
/// @notice returns how many BMI tokens needs to approve in order to submit a claim
function getClaimApprovalAmount(address user) external view returns (uint256);
/// @notice upserts a withdraw request
/// @dev prevents adding a request if an already pending or ready request is open.
/// @param _tokensToWithdraw uint256 amount of tokens to withdraw
function requestWithdrawal(uint256 _tokensToWithdraw) external;
function listUserLeveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _userLeveragePools);
function countUserLeveragePools() external view returns (uint256);
/// @notice get utilization rate of the pool on chain
function getUtilizationRatioPercentage(bool withLeverage) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IYieldGenerator {
enum DefiProtocols {AAVE, COMPOUND, YEARN}
struct DefiProtocol {
uint256 targetAllocation;
uint256 currentAllocation;
uint256 rebalanceWeight;
uint256 depositedAmount;
bool whiteListed;
bool threshold;
bool withdrawMax;
// new state post v2
uint256 totalValue;
uint256 depositCost;
}
/// @notice deposit stable coin into multiple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to deposit
function deposit(uint256 amount) external returns (uint256);
/// @notice withdraw stable coin from mulitple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to withdraw
function withdraw(uint256 amount) external returns (uint256);
/// @notice set the protocol settings for each defi protocol (allocations, whitelisted, depositCost), access: owner
/// @param whitelisted bool[] list of whitelisted values for each protocol
/// @param allocations uint256[] list of allocations value for each protocol
/// @param depositCost uint256[] list of depositCost values for each protocol
function setProtocolSettings(
bool[] calldata whitelisted,
uint256[] calldata allocations,
uint256[] calldata depositCost
) external;
/// @notice Claims farmed tokens and sends it to the reinsurance pool
function claimRewards() external;
/// @notice returns defi protocol info by its index
/// @param index uint256 the index of the defi protocol
function defiProtocol(uint256 index)
external
view
returns (
uint256 _targetAllocation,
uint256 _currentAllocation,
uint256 _rebalanceWeight,
uint256 _depositedAmount,
bool _whiteListed,
bool _threshold,
uint256 _totalValue,
uint256 _depositCost
);
function reevaluateDefiProtocolBalances()
external
returns (uint256 _totalDeposit, uint256 _lostAmount);
function defiHardRebalancing() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
} | @notice claim rewards for all defi protocols and send them to reinsurance pool, access: owner | function claimRewards() external override onlyOwner {
for (uint256 i = 0; i < PROTOCOLS_NUMBER; i++) {
IDefiProtocol(defiProtocolsAddresses[i]).claimRewards();
}
}
| 9,888,551 | [
1,
14784,
283,
6397,
364,
777,
1652,
77,
16534,
471,
1366,
2182,
358,
283,
2679,
295,
1359,
2845,
16,
2006,
30,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7516,
17631,
14727,
1435,
3903,
3849,
1338,
5541,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
24245,
55,
67,
9931,
31,
277,
27245,
288,
203,
5411,
467,
3262,
77,
5752,
12,
536,
77,
21657,
7148,
63,
77,
65,
2934,
14784,
17631,
14727,
5621,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-16
*/
//$REDSHIB is aiming to reach sufficient funding from its token launch to be able to
//finance its main utility which is a Dating dApp platform running on the blockchain
//and utilizing its benefits in the dating market.
// Telegram: https://t.me/redshibtoken
// Website: www.RedShib.com
// Verified using https://dapp.tools
// hevm: flattened sources of src/RedShibf.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
////// lib/openzeppelin-contracts/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
/* pragma solidity ^0.8.0; */
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
////// lib/openzeppelin-contracts/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
/* pragma solidity ^0.8.0; */
/* import "../utils/Context.sol"; */
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
/* pragma solidity ^0.8.0; */
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol)
/* pragma solidity ^0.8.0; */
/* import "../IERC20.sol"; */
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol)
/* pragma solidity ^0.8.0; */
/* import "./IERC20.sol"; */
/* import "./extensions/IERC20Metadata.sol"; */
/* import "../../utils/Context.sol"; */
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
////// lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
/* pragma solidity ^0.8.0; */
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
////// src/IUniswapV2Factory.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
////// src/IUniswapV2Pair.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
////// src/IUniswapV2Router02.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
////// src/RedShib.sol
/* pragma solidity >=0.8.10; */
/* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */
/* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */
/* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */
/* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */
/* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */
/* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */
/* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */
contract Redshib is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event devWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Red Shib", "REDSHIB") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 6;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 3;
uint256 _sellMarketingFee = 6;
uint256 _sellLiquidityFee = 3;
uint256 _sellDevFee = 3;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransactionAmount = 10_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn
maxWallet = 20_000_000 * 1e18; // 2% from total supply maxWallet
swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0x9b1B9D52d6a2c2850DEe69631D6E6DD4a40c511B); // set as marketing wallet
devWallet = address(0x9b1B9D52d6a2c2850DEe69631D6E6DD4a40c511B); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 5) / 1000,
"Swap amount cannot be higher than 0.5% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000) / 1e18,
"Cannot set maxTransactionAmount lower than 0.1%"
);
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet)
external
onlyOwner
{
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
//when sell
else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
} else if (!_isExcludedMaxTransactionAmount[to]) {
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if (takeFee) {
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
// on buy
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success, ) = address(devWallet).call{value: ethForDev}("");
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function setAutoLPBurnSettings(
uint256 _frequencyInSeconds,
uint256 _percent,
bool _Enabled
) external onlyOwner {
require(
_frequencyInSeconds >= 600,
"cannot set buyback more often than every 10 minutes"
);
require(
_percent <= 1000 && _percent >= 0,
"Must set auto LP burn percent between 0% and 10%"
);
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent)
external
onlyOwner
returns (bool)
{
require(
block.timestamp > lastManualLpBurnTime + manualBurnFrequency,
"Must wait for cooldown to finish"
);
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | set as marketing wallet
| marketingWallet = address(0x9b1B9D52d6a2c2850DEe69631D6E6DD4a40c511B); | 1,159,295 | [
1,
542,
487,
13667,
310,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
13667,
310,
16936,
273,
1758,
12,
20,
92,
29,
70,
21,
38,
29,
40,
9401,
72,
26,
69,
22,
71,
6030,
3361,
1639,
73,
8148,
4449,
21,
40,
26,
41,
26,
5698,
24,
69,
7132,
71,
25,
2499,
38,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/100/0x2350d72333dd4f41a358cCBCF9D433F4b4829e3d/sources/AMBBridgeHelper.sol | recover number of confirmations sent by oracles | function getSignatures(bytes calldata _message) external view returns(bytes memory) {
bytes32 msgHash = keccak256(abi.encodePacked(_message));
uint256 signed = AMBcontract.numMessagesSigned(msgHash);
require(AMBcontract.isAlreadyProcessed(signed), "message hasn't been confirmed");
signed = signed & 0x8fffffffffffffffffffffffffffffffffffffffffff;
require(signed < 0x100);
bytes memory signatures = new bytes(1 + signed * 65);
assembly {
mstore8(add(signatures, 32), signed)
}
for (uint256 i = 0; i < signed; i++) {
bytes memory sig = AMBcontract.signature(msgHash, i);
(bytes32 r, bytes32 s, uint8 v) = unpackSignature(sig);
assembly {
mstore8(add(add(signatures, 33), i), v)
mstore(add(add(add(signatures, 33), signed), mul(i, 32)), r)
mstore(add(add(add(signatures, 33), mul(signed, 33)), mul(i, 32)), s)
}
}
return signatures;
}
| 16,655,785 | [
1,
266,
3165,
1300,
434,
6932,
1012,
3271,
635,
578,
69,
9558,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
14167,
2790,
12,
3890,
745,
892,
389,
2150,
13,
3903,
1476,
1135,
12,
3890,
3778,
13,
288,
203,
3639,
1731,
1578,
1234,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
2150,
10019,
203,
3639,
2254,
5034,
6726,
273,
432,
7969,
16351,
18,
2107,
5058,
12294,
12,
3576,
2310,
1769,
203,
203,
3639,
2583,
12,
2192,
38,
16351,
18,
291,
9430,
13533,
12,
5679,
3631,
315,
2150,
13342,
1404,
2118,
19979,
8863,
203,
540,
203,
3639,
6726,
273,
6726,
473,
374,
92,
28,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
18217,
74,
31,
203,
540,
203,
3639,
2583,
12,
5679,
411,
374,
92,
6625,
1769,
203,
540,
203,
3639,
1731,
3778,
14862,
273,
394,
1731,
12,
21,
397,
6726,
380,
15892,
1769,
203,
540,
203,
3639,
19931,
288,
203,
5411,
312,
2233,
28,
12,
1289,
12,
30730,
16,
3847,
3631,
6726,
13,
203,
3639,
289,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
6726,
31,
277,
27245,
288,
203,
5411,
1731,
3778,
3553,
273,
432,
7969,
16351,
18,
8195,
12,
3576,
2310,
16,
277,
1769,
203,
5411,
261,
3890,
1578,
436,
16,
1731,
1578,
272,
16,
2254,
28,
331,
13,
273,
6167,
5374,
12,
7340,
1769,
203,
5411,
19931,
288,
203,
7734,
312,
2233,
28,
12,
1289,
12,
1289,
12,
30730,
16,
13159,
3631,
277,
3631,
331,
13,
203,
7734,
312,
2233,
12,
1289,
12,
1289,
12,
1289,
12,
30730,
16,
13159,
3631,
6726,
3631,
14064,
12,
77,
16,
3847,
13,
2
] |
./partial_match/1/0x695264D984A5E45C2d89f261C8668d6C1F7D214c/sources/IporProtocolRouter.sol | By storing the original value once again, a refund is triggered (see https:eips.ethereum.org/EIPS/eip-2200) | function _nonReentrantAfter() internal {
if (StorageLib.getReentrancyStatus().value == _ENTERED) {
StorageLib.getReentrancyStatus().value = _NOT_ENTERED;
}
}
| 16,153,399 | [
1,
858,
15729,
326,
2282,
460,
3647,
3382,
16,
279,
16255,
353,
10861,
261,
5946,
2333,
30,
73,
7146,
18,
546,
822,
379,
18,
3341,
19,
41,
2579,
55,
19,
73,
625,
17,
3787,
713,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
5836,
426,
8230,
970,
4436,
1435,
2713,
288,
203,
3639,
309,
261,
3245,
5664,
18,
588,
426,
8230,
12514,
1482,
7675,
1132,
422,
389,
12278,
2056,
13,
288,
203,
5411,
5235,
5664,
18,
588,
426,
8230,
12514,
1482,
7675,
1132,
273,
389,
4400,
67,
12278,
2056,
31,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.13;
contract ERC20 {
function balanceOf(address who) public constant returns (uint);
function allowance(address owner, address spender) public constant returns (uint);
function transfer(address to, uint value) public returns (bool ok);
function transferFrom(address from, address to, uint value) public returns (bool ok);
function approve(address spender, uint value) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value) ;
event Approval(address indexed owner, address indexed spender, uint value);
}
contract SafeMath {
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal pure returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract StandardToken is ERC20, SafeMath {
/* Token supply got increased and a new owner received these tokens */
event Minted(address receiver, uint amount);
/* Actual balances of token holders */
mapping(address => uint) balances;
/* approve() allowances */
mapping (address => mapping (address => uint)) allowed;
function isToken() public pure returns (bool yes) {
return true;
}
function transfer(address _to, uint _value) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
uint _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _address) constant public returns (uint balance) {
return balances[_address];
}
function approve(address _spender, uint _value) public returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract DESToken is StandardToken {
string public name = "Decentralized Escrow Service";
string public symbol = "DES";
uint public decimals = 8;//Разрядность токена
uint public HardCapEthereum = 66666000000000000000000 wei;//Максимальное количество собранного Ethereum - 66 666 ETH (задано в wei)
//Массив с замороженными адресами, которым запрещено осуществять переводы токенов
mapping (address => bool) public noTransfer;
// Время начала ICO и время окончания ICO
uint constant public TimeStart = 1511956800;//Константа - время начала ICO - 29.11.2017 в 15:00 по Мск
uint public TimeEnd = 1514375999;//Время окончания ICO - 27.12.2017 в 14:59:59 по мск
// Время окончания бонусных этапов (недель)
uint public TimeWeekOne = 1512561600;//1000 DES – начальная цена – 1-ая неделя
uint public TimeWeekTwo = 1513166400;//800 DES – 2-ая неделя
uint public TimeWeekThree = 1513771200;//666,666 DES – 3-ая неделя
uint public TimeTransferAllowed = 1516967999;//Переводы токенов разрешены через месяц (30 суток = 2592000 секунд) после ICO
//Пулы ICO (различное время выхода на биржу: запрет некоторым пулам перечисления токенов до определенного времени)
uint public PoolPreICO = 0;//Человек в ЛК указывает свой адрес эфириума, на котором хранятся DEST или DESP и ему на этот адрес приходят токены DES в таком же количестве + ещё 50%
uint public PoolICO = 0;//Пул ICO - выход на биржу через 1 месяц
uint public PoolTeam = 0;//Пул команды - выход на биржу через 1 месяц. 15%
uint public PoolAdvisors = 0;//Пул эдвайзеров - выход на биржу через 1 месяц. 7%
uint public PoolBounty = 0;//Пул баунти кампании - выход на биржу через 1 месяц. 3%
//Стоимость токенов на различных этапах
uint public PriceWeekOne = 10000000 wei;//Стоимость токена во время недели 1
uint public PriceWeekTwo = 12500000 wei;//Стоимость токена во время недели 2
uint public PriceWeekThree = 15000000 wei;//Стоимость токена во время недели 3
uint public PriceWeekFour = 17500000 wei;//Стоимость токена во время недели 4
uint public PriceManual = 0 wei;//Стоимость токена, установленная вручную
//Технические переменные состояния ICO
bool public ICOPaused = false; //Основатель может активировать данный параметр (true), чтобы приостановить ICO на неопределенный срок
bool public ICOFinished = false; //ICO было завершено
//Технические переменные для хранения данных статистики
uint public StatsEthereumRaised = 0 wei;//Переменная сохранит в себе количество собранного Ethereum
uint public StatsTotalSupply = 0;//Общее количество выпущенных токенов
//События
event Buy(address indexed sender, uint eth, uint fbt);//Покупка токенов
event TokensSent(address indexed to, uint value);//Токены отправлены на адрес
event ContributionReceived(address indexed to, uint value);//Вложение получено
event PriceChanged(string _text, uint _tokenPrice);//Стоимость токена установлена вручную
event TimeEndChanged(string _text, uint _timeEnd);//Время окончания ICO изменено вручную
event TimeTransferAllowanceChanged(string _text, uint _timeAllowance);//Время, до которого запрещены переводы токенов, изменено вручную
address public owner = 0x0;
//Административные действия 0xE7F7d6cBCdC1fE78F938Bfaca6eA49604cB58D33
address public wallet = 0x0;
//Кошелек сбора средств 0x51559efc1acc15bcafc7e0c2fb440848c136a46b
function DESToken(address _owner, address _wallet) public payable {
owner = _owner;
wallet = _wallet;
balances[owner] = 0;
balances[wallet] = 0;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
//Приостановлено ли ICO или запущено
modifier isActive() {
require(!ICOPaused);
_;
}
//Транзакция получена - запустить функцию покупки
function() public payable {
buy();
}
//Установка стоимости токена вручную. Если значение больше 0, токены продаются по установленной вручную цене
function setTokenPrice(uint _tokenPrice) external onlyOwner {
PriceManual = _tokenPrice;
PriceChanged("New price is ", _tokenPrice);
}
//Установка времени окончания ICO
function setTimeEnd(uint _timeEnd) external onlyOwner {
TimeEnd = _timeEnd;
TimeEndChanged("New ICO End Time is ", _timeEnd);
}
//Установка времени, до которого запрещены переводы токенов
function setTimeTransferAllowance(uint _timeAllowance) external onlyOwner {
TimeTransferAllowed = _timeAllowance;
TimeTransferAllowanceChanged("Token transfers will be allowed at ", _timeAllowance);
}
// Запретить определенному покупателю осуществлять переводы его токенов
// @параметр target Адрес покупателя, на который установить запрет
// @параметр allow Установить запрет (true) или запрет снят (false)
function disallowTransfer(address target, bool disallow) external onlyOwner {
noTransfer[target] = disallow;
}
//Завершить ICO и создать пулы токенов (команда, баунти, эдвайзеры)
function finishCrowdsale() external onlyOwner returns (bool) {
if (ICOFinished == false) {
PoolTeam = StatsTotalSupply*1998/10000;//Пул команды - выход на биржу через 1 месяц. 15%
PoolAdvisors = StatsTotalSupply*9324/100000;//Пул эдвайзеров - выход на биржу через 1 месяц. 7%
PoolBounty = StatsTotalSupply*3996/100000;//Пул баунти кампании - выход на биржу через 1 месяц. 3%
uint poolTokens = 0;
poolTokens = safeAdd(poolTokens,PoolTeam);
poolTokens = safeAdd(poolTokens,PoolAdvisors);
poolTokens = safeAdd(poolTokens,PoolBounty);
//Зачислить на счет основателя токены пула команды, эдвайзеров и баунти
require(poolTokens>0);//Количество токенов должно быть больше 0
balances[owner] = safeAdd(balances[owner], poolTokens);
StatsTotalSupply = safeAdd(StatsTotalSupply, poolTokens);//Обновляем общее количество выпущенных токенов
Transfer(0, this, poolTokens);
Transfer(this, owner, poolTokens);
ICOFinished = true;//ICO завершено
}
}
//Функция возвращает текущую стоимость в wei 1 токена
function price() public constant returns (uint) {
if(PriceManual > 0){return PriceManual;}
if(now >= TimeStart && now < TimeWeekOne){return PriceWeekOne;}
if(now >= TimeWeekOne && now < TimeWeekTwo){return PriceWeekTwo;}
if(now >= TimeWeekTwo && now < TimeWeekThree){return PriceWeekThree;}
if(now >= TimeWeekThree){return PriceWeekFour;}
}
// Создать `amount` токенов и отправить их `target`
// @параметр target Адрес получателя токенов
// @параметр amount Количество создаваемых токенов
function sendPreICOTokens(address target, uint amount) onlyOwner external {
require(amount>0);//Количество токенов должно быть больше 0
balances[target] = safeAdd(balances[target], amount);
StatsTotalSupply = safeAdd(StatsTotalSupply, amount);//Обновляем общее количество выпущенных токенов
Transfer(0, this, amount);
Transfer(this, target, amount);
PoolPreICO = safeAdd(PoolPreICO,amount);//Обновляем общее количество токенов в пуле Pre-ICO
}
// Создать `amount` токенов и отправить их `target`
// @параметр target Адрес получателя токенов
// @параметр amount Количество создаваемых токенов
function sendICOTokens(address target, uint amount) onlyOwner external {
require(amount>0);//Количество токенов должно быть больше 0
balances[target] = safeAdd(balances[target], amount);
StatsTotalSupply = safeAdd(StatsTotalSupply, amount);//Обновляем общее количество выпущенных токенов
Transfer(0, this, amount);
Transfer(this, target, amount);
PoolICO = safeAdd(PoolICO,amount);//Обновляем общее количество токенов в пуле Pre-ICO
}
// Перечислить `amount` командных токенов на адрес `target` со счета основателя (администратора) после завершения ICO
// @параметр target Адрес получателя токенов
// @параметр amount Количество перечисляемых токенов
function sendTeamTokens(address target, uint amount) onlyOwner external {
require(ICOFinished);//Возможно только после завершения ICO
require(amount>0);//Количество токенов должно быть больше 0
require(amount>=PoolTeam);//Количество токенов должно быть больше или равно размеру пула команды
require(balances[owner]>=PoolTeam);//Количество токенов должно быть больше или равно балансу основателя
balances[owner] = safeSub(balances[owner], amount);//Вычитаем токены у администратора (основателя)
balances[target] = safeAdd(balances[target], amount);//Добавляем токены на счет получателя
PoolTeam = safeSub(PoolTeam, amount);//Обновляем общее количество токенов пула команды
TokensSent(target, amount);//Публикуем событие в блокчейн
Transfer(owner, target, amount);//Осуществляем перевод
noTransfer[target] = true;//Вносим получателя в базу аккаунтов, которым 1 месяц после ICO запрещено осуществлять переводы токенов
}
// Перечислить `amount` токенов эдвайзеров на адрес `target` со счета основателя (администратора) после завершения ICO
// @параметр target Адрес получателя токенов
// @параметр amount Количество перечисляемых токенов
function sendAdvisorsTokens(address target, uint amount) onlyOwner external {
require(ICOFinished);//Возможно только после завершения ICO
require(amount>0);//Количество токенов должно быть больше 0
require(amount>=PoolAdvisors);//Количество токенов должно быть больше или равно размеру пула эдвайзеров
require(balances[owner]>=PoolAdvisors);//Количество токенов должно быть больше или равно балансу основателя
balances[owner] = safeSub(balances[owner], amount);//Вычитаем токены у администратора (основателя)
balances[target] = safeAdd(balances[target], amount);//Добавляем токены на счет получателя
PoolAdvisors = safeSub(PoolAdvisors, amount);//Обновляем общее количество токенов пула эдвайзеров
TokensSent(target, amount);//Публикуем событие в блокчейн
Transfer(owner, target, amount);//Осуществляем перевод
noTransfer[target] = true;//Вносим получателя в базу аккаунтов, которым 1 месяц после ICO запрещено осуществлять переводы токенов
}
// Перечислить `amount` баунти токенов на адрес `target` со счета основателя (администратора) после завершения ICO
// @параметр target Адрес получателя токенов
// @параметр amount Количество перечисляемых токенов
function sendBountyTokens(address target, uint amount) onlyOwner external {
require(ICOFinished);//Возможно только после завершения ICO
require(amount>0);//Количество токенов должно быть больше 0
require(amount>=PoolBounty);//Количество токенов должно быть больше или равно размеру пула баунти
require(balances[owner]>=PoolBounty);//Количество токенов должно быть больше или равно балансу основателя
balances[owner] = safeSub(balances[owner], amount);//Вычитаем токены у администратора (основателя)
balances[target] = safeAdd(balances[target], amount);//Добавляем токены на счет получателя
PoolBounty = safeSub(PoolBounty, amount);//Обновляем общее количество токенов пула баунти
TokensSent(target, amount);//Публикуем событие в блокчейн
Transfer(owner, target, amount);//Осуществляем перевод
noTransfer[target] = true;//Вносим получателя в базу аккаунтов, которым 1 месяц после ICO запрещено осуществлять переводы токенов
}
//Функция покупки токенов на ICO
function buy() public payable returns(bool) {
require(msg.sender != owner);//Основатели не могут покупать токены
require(msg.sender != wallet);//Основатели не могут покупать токены
require(!ICOPaused);//Покупка разрешена, если ICO не приостановлено
require(!ICOFinished);//Покупка разрешена, если ICO не завершено
require(msg.value >= price());//Полученная сумма в wei должна быть больше стоимости 1 токена
require(now >= TimeStart);//Условие продажи - ICO началось
require(now <= TimeEnd);//Условие продажи - ICO не завершено
uint tokens = msg.value/price();//Количество токенов, которое должен получить покупатель
require(safeAdd(StatsEthereumRaised, msg.value) <= HardCapEthereum);//Собранный эфир не больше hard cap
require(tokens>0);//Количество токенов должно быть больше 0
wallet.transfer(msg.value);//Отправить полученные ETH на кошелек сбора средств
//Зачисление токенов на счет покупателя
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
StatsTotalSupply = safeAdd(StatsTotalSupply, tokens);//Обновляем общее количество выпущенных токенов
Transfer(0, this, tokens);
Transfer(this, msg.sender, tokens);
StatsEthereumRaised = safeAdd(StatsEthereumRaised, msg.value);//Обновляем цифру собранных ETH
PoolICO = safeAdd(PoolICO, tokens);//Обновляем размер пула ICO
//Записываем события в блокчейн
Buy(msg.sender, msg.value, tokens);
TokensSent(msg.sender, tokens);
ContributionReceived(msg.sender, msg.value);
return true;
}
function EventEmergencyStop() public onlyOwner() {ICOPaused = true;}//Остановить ICO (в случае непредвиденных обстоятельств)
function EventEmergencyContinue() public onlyOwner() {ICOPaused = false;}//Продолжить ICO
//Если переводы токенов для всех участников еще не разрешены (1 месяц после ICO), проверяем, участник ли это Pre-ICO. Если нет, запрещаем перевод
function transfer(address _to, uint _value) public isActive() returns (bool success) {
if(now >= TimeTransferAllowed){
if(noTransfer[msg.sender]){noTransfer[msg.sender] = false;}//Если переводы разрешены по времени, разрешаем их отправителю
}
if(now < TimeTransferAllowed){require(!noTransfer[msg.sender]);}//Если переводы еще не разрешены по времени, переводить могут только участники Pre-ICO
return super.transfer(_to, _value);
}
/**
* ERC 20 Standard Token interface transfer function
*
* Prevent transfers until halt period is over.
*/
function transferFrom(address _from, address _to, uint _value) public isActive() returns (bool success) {
if(now >= TimeTransferAllowed){
if(noTransfer[msg.sender]){noTransfer[msg.sender] = false;}//Если переводы разрешены по времени, разрешаем их отправителю
}
if(now < TimeTransferAllowed){require(!noTransfer[msg.sender]);}//Если переводы еще не разрешены по времени, переводить могут только участники Pre-ICO
return super.transferFrom(_from, _to, _value);
}
//Сменить владельца
function changeOwner(address _to) public onlyOwner() {
balances[_to] = balances[owner];
balances[owner] = 0;
owner = _to;
}
//Сменить адрес кошелька для сбора средств
function changeWallet(address _to) public onlyOwner() {
balances[_to] = balances[wallet];
balances[wallet] = 0;
wallet = _to;
}
}
| Установка стоимости токена вручную. Если значение больше 0, токены продаются по установленной вручную цене | function setTokenPrice(uint _tokenPrice) external onlyOwner {
PriceManual = _tokenPrice;
PriceChanged("New price is ", _tokenPrice);
}
| 7,219,948 | [
1,
145,
101,
146,
228,
146,
229,
145,
113,
145,
126,
145,
127,
145,
115,
145,
123,
145,
113,
225,
146,
228,
146,
229,
145,
127,
145,
121,
145,
125,
145,
127,
146,
228,
146,
229,
145,
121,
225,
146,
229,
145,
127,
145,
123,
145,
118,
145,
126,
145,
113,
225,
145,
115,
146,
227,
146,
230,
146,
234,
145,
126,
146,
230,
146,
241,
18,
225,
145,
248,
146,
228,
145,
124,
145,
121,
225,
145,
120,
145,
126,
145,
113,
146,
234,
145,
118,
145,
126,
145,
121,
145,
118,
225,
145,
114,
145,
127,
145,
124,
146,
239,
146,
235,
145,
118,
374,
16,
225,
146,
229,
145,
127,
145,
123,
145,
118,
145,
126,
146,
238,
225,
145,
128,
146,
227,
145,
127,
145,
117,
145,
113,
146,
241,
146,
229,
146,
228,
146,
242,
225,
145,
128,
145,
127,
225,
146,
230,
146,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
22629,
5147,
12,
11890,
389,
2316,
5147,
13,
3903,
1338,
5541,
288,
203,
3639,
20137,
25139,
273,
389,
2316,
5147,
31,
203,
3639,
20137,
5033,
2932,
1908,
6205,
353,
3104,
389,
2316,
5147,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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 Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @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 {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpauseunpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @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
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
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 returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @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
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit 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;
emit MintFinished();
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
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
{
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal
{
require(_value <= balances[_who]);
// 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
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/**
* @title VnbigToken Token
* @dev Global digital painting asset platform token.
*/
contract VnbigToken is PausableToken, MintableToken, BurnableToken {
using SafeMath for uint256;
string public name = "VNBIG Token";
string public symbol = "VNBT";
uint256 public decimals = 18;
uint256 INITIAL_SUPPLY = 10000000000 * (10 ** uint256(decimals));
event UpdatedTokenInformation(string name, string symbol);
mapping (address => bool) public frozenAccount;
event FrozenFunds(address indexed to, bool frozen);
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = totalSupply_;
emit Transfer(address(0), msg.sender, totalSupply_);
}
function() public payable {
revert(); //if ether is sent to this address, send it back.
}
function transfer(address _to, uint256 _value) public returns (bool)
{
require(!frozenAccount[msg.sender]);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
require(!frozenAccount[msg.sender]);
return super.transferFrom(_from, _to, _value);
}
function freezeAccount(address _to, bool freeze) public onlyOwner {
frozenAccount[_to] = freeze;
emit FrozenFunds(_to, freeze);
}
/**
* @dev Update the symbol.
* @param _tokenSymbol The symbol name.
*/
function setTokenInformation(string _tokenName, string _tokenSymbol) public onlyOwner {
name = _tokenName;
symbol = _tokenSymbol;
emit UpdatedTokenInformation(name, symbol);
}
} | * @dev Update the symbol. @param _tokenSymbol The symbol name./ | function setTokenInformation(string _tokenName, string _tokenSymbol) public onlyOwner {
name = _tokenName;
symbol = _tokenSymbol;
emit UpdatedTokenInformation(name, symbol);
}
| 7,682,371 | [
1,
1891,
326,
3273,
18,
225,
389,
2316,
5335,
1021,
3273,
508,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
22629,
5369,
12,
1080,
389,
2316,
461,
16,
533,
389,
2316,
5335,
13,
1071,
1338,
5541,
288,
203,
3639,
508,
273,
389,
2316,
461,
31,
203,
3639,
3273,
273,
389,
2316,
5335,
31,
203,
3639,
3626,
19301,
1345,
5369,
12,
529,
16,
3273,
1769,
203,
565,
289,
7010,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
/**
* @title TokenVesting
* @dev This contract is used to award vesting tokens to wallets.
* Multiple wallets can be vested to using this contract, all using the same vesting schedule.
*/
contract TokenVesting is OwnableUpgradeable {
using SafeERC20 for IERC20;
/**
* Emitted when vesting tokens are rewarded to a beneficiary
*/
event Awarded(address indexed beneficiary, uint256 amount, bool revocable);
/**
* Emitted when vesting tokens are released to a beneficiary
*/
event Released(address indexed beneficiary, uint256 amount);
/**
* Emitted when vesting tokens are revoked from a beneficiary
*/
event Revoked(address indexed beneficiary, uint256 revokedAmount);
// Global vesting parameters for this contract
uint256 public vestingStart;
uint256 public vestingCliff;
uint256 public vestingDuration;
uint256 public releasedTotal;
struct TokenAward {
uint256 amount;
uint256 released;
bool revocable;
bool revoked;
}
// Tracks the token awards for each user (user => award)
mapping(address => TokenAward) public awards;
IERC20 public targetToken;
function __TokenVesting_init(
uint256 start,
uint256 cliff,
uint256 duration,
address token
) internal initializer {
__Ownable_init();
require(cliff <= duration, "Cliff must be less than duration");
vestingStart = start;
vestingCliff = start + cliff;
vestingDuration = duration;
targetToken = IERC20(token);
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param beneficiary Who the tokens are being released to
*/
function release(address beneficiary) public {
uint256 unreleased = getReleasableAmount(beneficiary);
require(unreleased > 0, "Nothing to release");
TokenAward storage award = getTokenAwardStorage(beneficiary);
award.released += unreleased;
targetToken.safeTransfer(beneficiary, unreleased);
releasedTotal += unreleased;
emit Released(beneficiary, unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* are transfered to the beneficiary, the rest are returned to the owner.
* @param beneficiary Who the tokens are being released to
*/
function revoke(address beneficiary) public onlyOwner {
TokenAward storage award = getTokenAwardStorage(beneficiary);
require(award.revocable, "Cannot be revoked");
require(!award.revoked, "Already revoked");
// Figure out how many tokens were owed up until revocation
uint256 unreleased = getReleasableAmount(beneficiary);
award.released += unreleased;
uint256 refund = award.amount - award.released;
// Mark award as revoked
award.revoked = true;
award.amount = award.released;
// Transfer owed vested tokens to beneficiary
targetToken.safeTransfer(beneficiary, unreleased);
// Transfer unvested tokens to owner (revoked amount)
targetToken.safeTransfer(owner(), refund);
emit Released(beneficiary, unreleased);
emit Revoked(beneficiary, refund);
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param beneficiary Who the tokens are being released to
*/
function getReleasableAmount(address beneficiary)
public
view
returns (uint256)
{
TokenAward memory award = getTokenAward(beneficiary);
return getVestedAmount(beneficiary) - award.released;
}
/**
* @dev Calculates the amount that has already vested.
* @param beneficiary Who the tokens are being released to
*/
function getVestedAmount(address beneficiary) public view returns (uint256) {
TokenAward memory award = getTokenAward(beneficiary);
if (block.number < vestingCliff) {
return 0;
} else if (
block.number >= vestingStart + vestingDuration || award.revoked
) {
return award.amount;
} else {
return (award.amount * (block.number - vestingStart)) / vestingDuration;
}
}
function _awardTokens(
address beneficiary,
uint256 amount,
bool revocable
) internal {
TokenAward storage award = getTokenAwardStorage(beneficiary);
award.amount += amount;
award.revocable = revocable;
emit Awarded(beneficiary, amount, revocable);
}
function getTokenAward(address beneficiary)
internal
view
returns (TokenAward memory)
{
TokenAward memory award = awards[beneficiary];
return award;
}
function getTokenAwardStorage(address beneficiary)
internal
view
returns (TokenAward storage)
{
TokenAward storage award = awards[beneficiary];
return award;
}
}
| * @dev Calculates the amount that has already vested but hasn't been released yet. @param beneficiary Who the tokens are being released to/ | function getReleasableAmount(address beneficiary)
public
view
returns (uint256)
{
TokenAward memory award = getTokenAward(beneficiary);
return getVestedAmount(beneficiary) - award.released;
}
| 5,440,060 | [
1,
10587,
326,
3844,
716,
711,
1818,
331,
3149,
1496,
13342,
1404,
2118,
15976,
4671,
18,
225,
27641,
74,
14463,
814,
3497,
83,
326,
2430,
854,
3832,
15976,
358,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
336,
17018,
345,
429,
6275,
12,
2867,
27641,
74,
14463,
814,
13,
203,
565,
1071,
203,
565,
1476,
203,
565,
1135,
261,
11890,
5034,
13,
203,
225,
288,
203,
565,
3155,
37,
2913,
3778,
279,
2913,
273,
9162,
37,
2913,
12,
70,
4009,
74,
14463,
814,
1769,
203,
565,
327,
11031,
3149,
6275,
12,
70,
4009,
74,
14463,
814,
13,
300,
279,
2913,
18,
9340,
72,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-26
*/
/*
guestlisted by @etherlect
____________________________________________________________
/ \
/______________________________________________________________\
| [+] [+] [+] [+] [+] CLUB [+] [+] [+] [+] [+] |
================================================================
| [+] [+] [+] [+] [+] [+] [+] [+] [+] [+] [+] [+] |
|----------------------------------------------------------- |
| +-+ | +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ | +-+ |
| |*| | |*| |*| |*| |*| |*| |*| |*| |*| |*| |*| | | | |
| +-+ | +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ | +-+ |
| [ ] | [+] [+] [+] [+] [+] [+] [+] [+] [+] [+] | [ ] |
| +-+ | +--+ | +-+ |
| | | | | | | | | |
==============================================================
_ -- --_ -- _ - __ - | | __ -- - _ -- --- _ _
_ --- __ - _-- __ - | | _ - __ -- ___ -- _ - __ -
__ -- - - _ - - | | _ - _ -- _ --- _ -- _ ---
*/
// File @openzeppelin/contracts/utils/introspection/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File @openzeppelin/contracts/security/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/utils/cryptography/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File contracts/GuestlistedLibrary.sol
pragma solidity ^0.8.12;
library GuestlistedLibrary {
struct Venue {
string name;
string location;
uint[2][] indexes;
string[] colors;
uint[] djIndexes;
}
struct DJ {
string firstName;
string lastName;
uint fontSize;
}
struct TokenData {
uint tokenId;
uint deterministicNumber;
uint randomNumber;
uint shapeRandomNumber;
uint shapeIndex;
string json;
string date;
string bg;
string color;
string shape;
string attributes;
string customMetadata;
string djFullName;
Venue venue;
DJ dj;
}
function toString(uint value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint(value % 10)));
value /= 10;
}
return string(buffer);
}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
// File contracts/Guestlisted.sol
pragma solidity ^0.8.12;
pragma experimental ABIEncoderV2;
contract Guestlisted is ERC721, ReentrancyGuard, Ownable {
using ECDSA for bytes32;
// -------------------------------------------------------------------------------------------------------
//
// Mint config
//
// @startIndex => Start index from which to mint tokens
// @endIndex => End index until which to mint tokens
// @remaining => Remaining tokens to mint
// @mintPrice => Current mint price (in WEI)
// @maxTokensPerTransaction => Max allowed tokens to mint per transaction
// @maxMintsPerWallet => Max allowed tokens to mint per wallet
// @version => Used as a key along with wallet address in mintedPerWallet mapping
// @isActive => State of the mint
// @isRandom => Mint strategy (random / predictable)
// @isOnlyForHolders => Allows only token holders to mint
// @isOnWhitelist => Request a signature of wallet address by whitelistSigner
// @whitelistSigner => Whitelist signer address which should be recovered while minting
//
// -------------------------------------------------------------------------------------------------------
struct MintConfig {
uint startIndex;
uint endIndex;
uint remaining;
uint mintPrice;
uint maxTokensPerTransaction;
uint maxMintsPerWallet;
uint version;
bool isActive;
bool isRandom;
bool isOnlyForHolders;
bool isOnWhitelist;
address whitelistSigner;
}
// ------------------------------------------------------------------------
//
// If exists, custom metadata is added in the JSON metadata of tokens:
//
// {
// ...other properties,
// name: value,
// name: value,
// ...
// }
//
// ------------------------------------------------------------------------
struct CustomMetadata {
string name;
string value;
}
// ------------------------------------------------------------------------
//
// If exists, custom attributes are added in the JSON metadata of tokens:
//
// {
// "attributes": {
// ...other attributes,
// {
// "display_type": displayType,
// "trait_type": traitType,
// "value": value
// }
// }
// }
//
// ------------------------------------------------------------------------
struct CustomAttribute {
string displayType;
string traitType;
string value;
}
// ------------------------------------------------------------------------
//
// Mapping storing the number of mints per wallet
// string(abi.encodePacked(walletAddress, mintConfig.version)) => nbMinted
//
// ------------------------------------------------------------------------
mapping(string => uint) private mintedPerWallet;
// --------------------------------------------------------
//
// Mapping storing already minted tokens
//
// --------------------------------------------------------
mapping(uint => uint) private mintCache;
// --------------------------------------------------------
//
// Mappings for eventual future custom metadata &
// attributes of tokens (added in the JSON if exists)
// tokenId => CustomAttribute[] / CustomMetadata[]
//
// --------------------------------------------------------
mapping(uint => CustomAttribute[]) public customAttributes;
mapping(uint => CustomMetadata[]) public customMetadata;
// --------------------------------------------------------
//
// Mapping returns if the color of the
// text should be white given a bg color
// bgColor (hex) => 0 (true) / 1 (false)
//
// --------------------------------------------------------
mapping(string => uint) public isTextColorWhite;
// --------------------------------------------------------
//
// Instantiation of global variables
//
// --------------------------------------------------------
uint public totalSupply;
uint public minted;
uint public burned;
bool public isBurnActive;
GuestlistedArtProxy public artProxyContract;
MintConfig public mintConfig;
GuestlistedLibrary.Venue[] private venues;
GuestlistedLibrary.DJ[] private djs;
// --------------------------------------------------------
//
// Returns the metadata of a token (base64 encoded JSON)
//
// --------------------------------------------------------
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token.");
// --------------------------------------------------------
//
// Get tokenData
//
// --------------------------------------------------------
GuestlistedLibrary.TokenData memory tokenData = getTokenData(_tokenId);
// --------------------------------------------------------
//
// Build attributes
//
// --------------------------------------------------------
tokenData.attributes = string(
abi.encodePacked(
'{"trait_type":"venue","value":"',
tokenData.venue.name,
'"}, {"trait_type":"dj","value":"',
tokenData.djFullName,
'"}, {"trait_type":"date","value":"',
tokenData.date,
'"}, {"trait_type":"shape","value":"',
tokenData.shape,
'"}, {"trait_type":"background","value":"',
tokenData.bg,
'"}, {"trait_type":"color","value":"',
tokenData.color,
'"}'
)
);
// --------------------------------------------------------
//
// Build custom attributes of the token if there is any
//
// --------------------------------------------------------
for (uint i = 0;i < customAttributes[_tokenId].length; i++) {
tokenData.attributes = string(
abi.encodePacked(
tokenData.attributes,
',{"display_type":"',
customAttributes[_tokenId][i].displayType,
'","trait_type":"',
customAttributes[_tokenId][i].traitType,
'","value":"',
customAttributes[_tokenId][i].value,
'"}'
)
);
}
// --------------------------------------------------------
//
// Build custom metadata of the token if there is any
//
// --------------------------------------------------------
for (uint i = 0;i < customMetadata[_tokenId].length; i++) {
tokenData.customMetadata = string(
abi.encodePacked(
tokenData.customMetadata,
',"',
customMetadata[_tokenId][i].name,
'":"',
customMetadata[_tokenId][i].value,
'"'
)
);
}
// --------------------------------------------------------
//
// Build final token metadata JSON
// (get the image from proxy art contract)
//
// --------------------------------------------------------
tokenData.json = Base64.encode(
bytes(
abi.encodePacked(
'{"name":"guestlisted #',
GuestlistedLibrary.toString(_tokenId),
' - ',
tokenData.djFullName,
' at ',
tokenData.venue.name,
'", "id": "',
GuestlistedLibrary.toString(_tokenId),
'", "description":"You are guestlisted.", "image":"',
artProxyContract.draw(tokenData),
'", "attributes":[',
tokenData.attributes,
']',
tokenData.customMetadata,
'}'
)
)
);
return string(abi.encodePacked("data:application/json;base64,", tokenData.json));
}
// --------------------------------------------------------
//
// Returns the data of a token (struct TokenData)
//
// --------------------------------------------------------
function getTokenData(uint256 _tokenId) private view returns (GuestlistedLibrary.TokenData memory) {
// --------------------------------------------------------
//
// Building tokenData used in the artProxyContract
//
// --------------------------------------------------------
GuestlistedLibrary.TokenData memory tokenData;
tokenData.tokenId = _tokenId;
tokenData.deterministicNumber = deterministic(GuestlistedLibrary.toString(_tokenId));
tokenData.randomNumber = random(GuestlistedLibrary.toString(_tokenId));
tokenData.shapeRandomNumber = tokenData.deterministicNumber % 100;
// --------------------------------------------------------
//
// Iterate indexes of each venue and pick the venue
// corresponding to the _tokenId
//
// --------------------------------------------------------
for (uint i = 0; i < venues.length; i++) {
for (uint j = 0; j < venues[i].indexes.length; j++) {
if (venues[i].indexes[j][0] <= _tokenId &&
venues[i].indexes[j][1] >= _tokenId) {
tokenData.venue = venues[i];
break;
}
}
}
// --------------------------------------------------------
//
// Pick the date, bg, text color and dj for a given
// tokenId and the selected venue
//
// --------------------------------------------------------
tokenData.date = getDate(_tokenId);
tokenData.bg = tokenData.venue.colors[tokenData.deterministicNumber % tokenData.venue.colors.length];
tokenData.color = isTextColorWhite[tokenData.bg] == 1 ? 'ffffff' : '393D3F';
tokenData.dj = djs[tokenData.venue.djIndexes[tokenData.deterministicNumber % tokenData.venue.djIndexes.length]];
// --------------------------------------------------------
//
// Pick a shape
//
// --------------------------------------------------------
// circle = 25% of chances
tokenData.shapeIndex = 0;
tokenData.shape = 'circle';
if (tokenData.shapeRandomNumber > 25 && tokenData.shapeRandomNumber <= 35) {
// line => 10% of chances
tokenData.shapeIndex = 4;
tokenData.shape = 'line';
} else if (tokenData.shapeRandomNumber > 35 && tokenData.shapeRandomNumber <= 55) {
// prism => 20% of chances
tokenData.shapeIndex = 1;
tokenData.shape = 'prism';
} else if (tokenData.shapeRandomNumber > 55 && tokenData.shapeRandomNumber <= 80) {
// cube => 25% of chances
tokenData.shapeIndex = 3;
tokenData.shape = 'cube';
} else if (tokenData.shapeRandomNumber > 80 && tokenData.shapeRandomNumber <= 100) {
// square => 20% of chances
tokenData.shapeIndex = 2;
tokenData.shape = 'square';
}
tokenData.djFullName = string(
abi.encodePacked(
tokenData.dj.firstName,
bytes(tokenData.dj.lastName).length == 0 ? '': string(abi.encodePacked(' ', tokenData.dj.lastName))
)
);
return tokenData;
}
// --------------------------------------------------------
//
// Returns the image of a token (base64 encoded SVG)
//
// --------------------------------------------------------
function tokenImage(uint256 _tokenId) public view returns (string memory) {
require(_exists(_tokenId), "tokenImage query for nonexistent token.");
return artProxyContract.draw(getTokenData(_tokenId));
}
// --------------------------------------------------------
//
// Returns a random index of token to mint depending on
// sender addr and current block timestamp & difficulty
//
// --------------------------------------------------------
function getRandomTokenIndex (address senderAddress) internal returns (uint) {
uint randomNumber = random(string(abi.encodePacked(senderAddress)));
uint i = (randomNumber % mintConfig.remaining) + mintConfig.startIndex;
// --------------------------------------------------------
//
// If there's a cache at mintCache[i] then use it
// otherwise use i itself
//
// --------------------------------------------------------
uint index = mintCache[i] == 0 ? i : mintCache[i];
// --------------------------------------------------------
//
// Grab a number from the tail & decrease remaining
//
// --------------------------------------------------------
mintCache[i] = mintCache[mintConfig.remaining - 1 + mintConfig.startIndex] == 0 ? mintConfig.remaining - 1 + mintConfig.startIndex : mintCache[mintConfig.remaining - 1 + mintConfig.startIndex];
mintConfig.remaining--;
return index;
}
function mint(uint _nbTokens, bytes memory signature) public payable nonReentrant {
require(mintConfig.isActive, "The mint is not active at the moment.");
require(_nbTokens > 0, "Number of tokens can not be less than or equal to 0.");
require(_nbTokens <= mintConfig.maxTokensPerTransaction, "Number of tokens can not be higher than allowed.");
require(mintConfig.remaining >= _nbTokens, "The mint would exceed the number of remaining tokens.");
require(mintConfig.mintPrice * _nbTokens == msg.value, "Sent ETH value is incorrect.");
// --------------------------------------------------------
//
// Check signature if mintConfig.isOnWhitelist is true
//
// --------------------------------------------------------
if (mintConfig.isOnWhitelist) {
address recoveredSigner = keccak256(abi.encodePacked(_msgSender())).toEthSignedMessageHash().recover(signature);
require(recoveredSigner == mintConfig.whitelistSigner, "Your wallet is not whitelisted.");
}
// --------------------------------------------------------
//
// Check if minter is holder if
// mintConfig.isOnlyForHolders is true
//
// --------------------------------------------------------
if (mintConfig.isOnlyForHolders) {
require(balanceOf(_msgSender()) > 0, "You have to own at least one token to mint more.");
}
// --------------------------------------------------------
//
// Check if minter has not already reached the
// limit of mints per wallet + update the mapping
// minterKey is composed of the wallet address and version
// version can be updated to reinit all wallets to 0 mints
//
// --------------------------------------------------------
string memory minterKey = string(abi.encodePacked(_msgSender(), mintConfig.version));
require(mintedPerWallet[minterKey] + _nbTokens <= mintConfig.maxMintsPerWallet, "Your wallet is not allowed to mint as many tokens.");
mintedPerWallet[minterKey] += _nbTokens;
// --------------------------------------------------------
//
// Mint depending on mint strategy: random / predictable
//
// --------------------------------------------------------
if (mintConfig.isRandom) {
for (uint i = 0; i < _nbTokens;i++) {
totalSupply++;
minted++;
_safeMint(_msgSender(), getRandomTokenIndex(_msgSender()));
}
} else {
for (uint i = 0; i < _nbTokens;i++) {
// --------------------------------------------------------
//
// Update mint cache & remaining before mint
//
// --------------------------------------------------------
totalSupply++;
minted++;
mintCache[minted] = mintConfig.remaining - 1 + mintConfig.startIndex;
mintConfig.remaining--;
_safeMint(_msgSender(), minted);
}
}
}
function burn(uint _tokenId) external {
require(isBurnActive, "Burning disabled.");
require(_exists(_tokenId), "The token does not exists.");
require(ownerOf(_tokenId) == _msgSender(), "You are not the owner of the token.");
totalSupply--;
burned++;
_burn(_tokenId);
}
// --------------------------------------------------------
//
// Returns a date for a tokenId
// date range: 01.01.22 - 28.12.25
//
// --------------------------------------------------------
function getDate (uint256 _tokenId) internal pure returns (string memory) {
uint deterministicNumber = deterministic(GuestlistedLibrary.toString(_tokenId));
uint day = deterministicNumber % 28 + 1;
uint month = deterministicNumber % 12 + 1;
uint yearDeterministic = deterministicNumber % 4;
string memory yearString = '22';
if (yearDeterministic == 1) yearString = '23';
else if (yearDeterministic == 2) yearString = '24';
else if (yearDeterministic == 3) yearString = '25';
string memory dayString = GuestlistedLibrary.toString(day);
if (day < 10) dayString = string(abi.encodePacked('0', dayString));
string memory monthString = GuestlistedLibrary.toString(month);
if (month < 10) monthString = string(abi.encodePacked('0', monthString));
return string(abi.encodePacked(dayString, '.', monthString, '.', yearString));
}
// --------------------------------------------------------
//
// Returns a deterministic number for an input
//
// --------------------------------------------------------
function deterministic (string memory input) internal pure returns (uint) {
return uint(keccak256(abi.encodePacked(input)));
}
// --------------------------------------------------------
//
// Returns a relatively random number for an input
// depending on current block timestamp & difficulty
//
// --------------------------------------------------------
function random (string memory input) internal view returns(uint) {
return uint(keccak256(abi.encodePacked(block.timestamp, block.difficulty, input)));
}
// --------------------------------------------------------
//
// Updates a venue in the storage at specified index
// Adds a new venue if the index is -1
//
// --------------------------------------------------------
function updateVenue (int _index, GuestlistedLibrary.Venue memory _venue) public onlyOwner {
require((_index == -1) || (uint(_index) < venues.length), 'Can not update non-existent venue.');
if (_index == -1) venues.push(_venue);
else venues[uint(_index)] = _venue;
}
function getVenueByIndex (uint _index) external view returns (GuestlistedLibrary.Venue memory) {
require(_index < venues.length , 'Venue does not exists.');
return venues[_index];
}
// --------------------------------------------------------
//
// Updates a dj in the storage at specified index
// Adds a new dj if the index is -1
//
// --------------------------------------------------------
function updateDJ (int _index, GuestlistedLibrary.DJ memory _dj) public onlyOwner {
require((_index == -1) || (uint(_index) <= djs.length - 1), 'Can not update non-existent dj.');
if (_index == -1) djs.push(_dj);
else djs[uint(_index)] = _dj;
}
function getDJByIndex (uint _index) external view returns (GuestlistedLibrary.DJ memory) {
require(_index < djs.length , 'DJ does not exists.');
return djs[_index];
}
function getMintedPerWallet (address minterAddress, uint version) external view returns (uint) {
string memory minterKey = string(abi.encodePacked(minterAddress, version));
return mintedPerWallet[minterKey];
}
function updateIsTextColorWhite (string memory bg, uint value) public onlyOwner {
require(value == 0 || value == 1, 'Wrong value.');
isTextColorWhite[bg] = value;
}
function updateArtProxyContract(address _artProxyContractAddress) public onlyOwner {
artProxyContract = GuestlistedArtProxy(_artProxyContractAddress);
}
// --------------------------------------------------------
//
// Update the adress used to sign & recover whitelists
//
// --------------------------------------------------------
function updateWhitelistSigner(address _whitelistSigner) external onlyOwner {
mintConfig.whitelistSigner = _whitelistSigner;
}
// ----------------------------------------------------------------
//
// Erease and update the custom metadata for a set of tokens.
// This metadata will be added to specified tokens in the
// tokenURI method.
//
// ----------------------------------------------------------------
function updateCustomMetadata (uint[] memory _tokenIds, CustomMetadata[] memory _customMetadata) external onlyOwner {
for (uint i = 0; i < _tokenIds.length; i++) {
delete customMetadata[_tokenIds[i]];
for (uint j = 0; j < _customMetadata.length; j++) {
customMetadata[_tokenIds[i]].push(_customMetadata[j]);
}
}
}
// ----------------------------------------------------------------
//
// Erease and update the custom attributes for a set of tokens.
// Those attributes will be added to specified tokens in the
// tokenURI method.
//
// ----------------------------------------------------------------
function updateCustomAttributes (uint[] memory _tokenIds, CustomAttribute[] memory _customAttributes) external onlyOwner {
for (uint i = 0; i < _tokenIds.length; i++) {
delete customAttributes[_tokenIds[i]];
for (uint j = 0; j < _customAttributes.length; j++) {
customAttributes[_tokenIds[i]].push(_customAttributes[j]);
}
}
}
function updateMintConfig(MintConfig memory _mintConfig) public onlyOwner {
mintConfig = _mintConfig;
}
function flipBurnState() external onlyOwner {
isBurnActive = !isBurnActive;
}
function flipMintState() external onlyOwner {
mintConfig.isActive = !mintConfig.isActive;
}
function withdraw() external onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
// ----------------------------------------------------------------
//
// Returns un array of tokens owned by an address
// (gas optimisation of tokenOfOwnerByIndex from ERC721Enumerable)
//
// ----------------------------------------------------------------
function tokensOfOwner(address _ownerAddress) public virtual view returns (uint[] memory) {
uint balance = balanceOf(_ownerAddress);
uint[] memory tokens = new uint[](balance);
uint tokenId;
uint found;
while (found < balance) {
if (_exists(tokenId) && ownerOf(tokenId) == _ownerAddress) {
tokens[found++] = tokenId;
}
tokenId++;
}
return tokens;
}
constructor(
address _artProxyContractAddress,
MintConfig memory _mintConfig,
GuestlistedLibrary.Venue[] memory _venues,
GuestlistedLibrary.DJ[] memory _djs,
string[] memory bgsWithWhiteTextColor,
uint[] memory _ownerReserve
) ERC721("guestlisted", "guestlist") Ownable() {
// --------------------------------------------------------
//
// Setup the art proxy contract instance
//
// --------------------------------------------------------
updateArtProxyContract(_artProxyContractAddress);
// --------------------------------------------------------
//
// Update the mintConfig
//
// --------------------------------------------------------
updateMintConfig(_mintConfig);
// --------------------------------------------------------
//
// Store venues
//
// --------------------------------------------------------
for (uint i = 0;i < _venues.length; i++) {
updateVenue(-1, _venues[i]);
}
// --------------------------------------------------------
//
// Store djs
//
// --------------------------------------------------------
for (uint i = 0;i < _djs.length; i++) {
updateDJ(-1, _djs[i]);
}
// --------------------------------------------------------
//
// Store backgounds that has white text color
//
// --------------------------------------------------------
for (uint i = 0; i < bgsWithWhiteTextColor.length; i++) {
updateIsTextColorWhite(bgsWithWhiteTextColor[i], 1);
}
// --------------------------------------------------------
//
// Mint owner reserved tokens
//
// --------------------------------------------------------
for (uint i = 0; i < _ownerReserve.length; i++) {
mintCache[_ownerReserve[i]] = mintConfig.remaining - 1 + mintConfig.startIndex;
totalSupply++;
minted++;
mintConfig.remaining--;
_safeMint(owner(), _ownerReserve[i]);
}
}
}
// --------------------------------------------------------
//
// Art proxy contract function signature
//
// --------------------------------------------------------
contract GuestlistedArtProxy {
function draw (GuestlistedLibrary.TokenData memory tokenData) public view returns (string memory) {}
} | -------------------------------------------------------- Art proxy contract function signature -------------------------------------------------------- | contract GuestlistedArtProxy {
function draw (GuestlistedLibrary.TokenData memory tokenData) public view returns (string memory) {}
} | 2,426,230 | [
1,
9634,
788,
225,
9042,
2889,
6835,
445,
3372,
13420,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
6467,
395,
18647,
4411,
3886,
288,
203,
565,
445,
3724,
261,
12978,
18647,
9313,
18,
1345,
751,
3778,
1147,
751,
13,
1071,
1476,
1135,
261,
1080,
3778,
13,
2618,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0xD5e2A366f9Df8d3772B0b8A0AafeCB0F03fD77B3/sources/DemoToken.sol | reward prediction at specific block | function getRewardPerBlock(uint blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return DemoPerBlock;
}
}
}
| 5,185,249 | [
1,
266,
2913,
8239,
622,
2923,
1203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4170,
359,
1060,
2173,
1768,
12,
11890,
1203,
1854,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
2629,
1854,
1545,
787,
1768,
15329,
203,
203,
5411,
2254,
5034,
1203,
9384,
22530,
273,
261,
2629,
1854,
18,
1717,
12,
1937,
1768,
13,
2934,
2892,
12,
457,
4245,
6450,
1769,
203,
203,
5411,
309,
12,
2629,
9384,
22530,
1648,
374,
15329,
203,
1171,
327,
27744,
83,
2173,
1768,
31,
203,
5411,
289,
203,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.3;
import './libs/SafeERC20.sol';
import './libs/Ownable.sol';
import './libs/SafeMath.sol';
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
using SafeERC20 for IERC20;
event TokensReleased(address token, uint256 amount);
event TokenVestingRevoked(address token);
// beneficiary of tokens after they are released
address private beneficiary;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private cliff;
uint256 private start;
uint256 private duration;
bool private revocable;
mapping(address => uint256) private released;
mapping(address => bool) private revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliffDuration duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliffDuration,
uint256 _duration,
bool _revocable,
address _owner
) {
require(
_beneficiary != address(0),
'TokenVesting: beneficiary is the zero address'
);
// solhint-disable-next-line max-line-length
require(
_cliffDuration <= _duration,
'TokenVesting: cliff is longer than duration'
);
require(_duration > 0, 'TokenVesting: duration is 0');
// solhint-disable-next-line max-line-length
require(
_start.add(_duration) > block.timestamp,
'TokenVesting: final time is before current time'
);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliffDuration);
start = _start;
transferOwnership(_owner);
}
/**
* @return the beneficiary of the tokens.
*/
function getBeneficiary() external view returns (address) {
return beneficiary;
}
/**
* @return the cliff time of the token vesting.
*/
function getCliff() external view returns (uint256) {
return cliff;
}
/**
* @return the start time of the token vesting.
*/
function getStart() external view returns (uint256) {
return start;
}
/**
* @return the duration of the token vesting.
*/
function getDuration() external view returns (uint256) {
return duration;
}
/**
* @return true if the vesting is revocable.
*/
function getRevocable() external view returns (bool) {
return revocable;
}
/**
* @return the amount of the token released.
*/
function getReleased(address token) external view returns (uint256) {
return released[token];
}
/**
* @return true if the token is revoked.
*/
function getRevoked(address token) external view returns (bool) {
return revoked[token];
}
/**
* @return the amount of the token vested.
*/
function getVestedAmount(IERC20 token) external view returns (uint256) {
return _vestedAmount(token);
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, 'TokenVesting: no tokens are due');
released[address(token)] = released[address(token)].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
emit TokensReleased(address(token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(revocable, 'TokenVesting: cannot revoke');
require(!revoked[address(token)], 'TokenVesting: token already revoked');
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[address(token)] = true;
token.safeTransfer(owner(), refund);
emit TokenVestingRevoked(address(token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(released[address(token)]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(released[address(token)]);
if (block.timestamp < cliff) {
return 0;
} else if (
block.timestamp >= start.add(duration) || revoked[address(token)]
) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
| * @return true if the token is revoked./ | function getRevoked(address token) external view returns (bool) {
return revoked[token];
}
| 5,463,662 | [
1,
2463,
638,
309,
326,
1147,
353,
22919,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
5561,
90,
14276,
12,
2867,
1147,
13,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
565,
327,
22919,
63,
2316,
15533,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/8453/0xc0d3C0D3C0D3c0D3C0D3C0d3C0D3c0D3c0d30015/sources/contracts/legacy/DeployerWhitelist.sol | * @notice Updates the owner of this contract. @param _owner Address of the new owner./ Prevent users from setting the whitelist owner to address(0) except via enableArbitraryContractDeployment. If you want to burn the whitelist owner, send it to any other address that doesn't have a corresponding knowable private key. | function setOwner(address _owner) external onlyOwner {
require(
_owner != address(0),
"DeployerWhitelist: can only be disabled via enableArbitraryContractDeployment"
);
emit OwnerChanged(owner, _owner);
owner = _owner;
}
| 16,772,460 | [
1,
5121,
326,
3410,
434,
333,
6835,
18,
225,
389,
8443,
5267,
434,
326,
394,
3410,
18,
19,
19412,
3677,
628,
3637,
326,
10734,
3410,
358,
1758,
12,
20,
13,
1335,
3970,
4237,
686,
3682,
3345,
8924,
6733,
18,
971,
1846,
2545,
358,
18305,
326,
10734,
3410,
16,
1366,
518,
358,
1281,
1308,
1758,
716,
3302,
1404,
1240,
279,
4656,
5055,
429,
3238,
498,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
31309,
12,
2867,
389,
8443,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
389,
8443,
480,
1758,
12,
20,
3631,
203,
5411,
315,
10015,
264,
18927,
30,
848,
1338,
506,
5673,
3970,
4237,
686,
3682,
3345,
8924,
6733,
6,
203,
3639,
11272,
203,
203,
3639,
3626,
16837,
5033,
12,
8443,
16,
389,
8443,
1769,
203,
3639,
3410,
273,
389,
8443,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.8.0;
contract Auction {
// declare the data types to be used
struct Item {
uint8 itemId; // id of the item
uint8 itemToken; // current token for this item.
int8 personId; // the id of the person who offers the highest bid.
string itemInfos; // info of the item
}
struct Person {
uint8 personId; // the id of the person
uint8 tokens; // the current tokens hold by the person
address personAddress; // address of this person
}
enum AuctionState {beforeStart, Started, End}
// declare variables to be used
Item[] private items;
Person[] private persons;
mapping (address => uint8) addressToPersonId;
AuctionState public auctionState;
uint8 public numberofPerson;
uint8 public numberofItem;
address public beneficiary_address;
constructor() {
beneficiary_address = msg.sender;
numberofPerson = 0;
}
modifier onlyBeneficiary{
// only beneficiary can call the function
require(msg.sender == beneficiary_address);
_;
}
modifier beforeStart {
// only call the function at the beforeStart state
require(auctionState == AuctionState.beforeStart, "the state of auction is not beforeStart");
_;
}
modifier onlyStarted {
// only call the function at the started state
require(auctionState == AuctionState.Started, "the sate of auction is not started");
_;
}
function registerPerson(address _address, uint8 tokens) public beforeStart onlyBeneficiary{
persons.push(Person(numberofPerson, tokens, _address));
addressToPersonId[_address] = numberofPerson;
numberofPerson = numberofPerson + 1;
}
function registerItem(string memory itemInfo) public beforeStart onlyBeneficiary{
items.push(Item(numberofItem, 0, -1, itemInfo));
numberofItem = numberofItem + 1;
}
function startAuction() public beforeStart onlyBeneficiary{
require(auctionState == AuctionState.beforeStart, "the state of auction is not beforeStart");
auctionState = AuctionState.Started;
}
function bid(uint8 tokens, uint8 itemId) public onlyStarted{
require(msg.sender == persons[addressToPersonId[msg.sender]].personAddress, "person is not registered");
require(itemId < numberofItem && itemId >= 0, "invalid itemId");
require(persons[addressToPersonId[msg.sender]].tokens > tokens, "no enough token");
require(items[itemId].itemToken < tokens, "bidding less the the highest offer");
uint8 tmp_amount;
// change the state of previous person
if (items[itemId].personId != -1){
tmp_amount = persons[uint8(items[itemId].personId)].tokens + items[itemId].itemToken;
persons[uint8(items[itemId].personId)].tokens = tmp_amount;
}
// change the state of item
items[itemId].itemToken = tokens;
items[itemId].personId = int8(persons[addressToPersonId[msg.sender]].personId);
// change the state of the person
tmp_amount = persons[addressToPersonId[msg.sender]].tokens - tokens;
persons[addressToPersonId[msg.sender]].tokens = tmp_amount;
}
function stopAuction() public onlyStarted onlyBeneficiary{
auctionState = AuctionState.End;
}
function addTokens(address _address, uint8 tokens) public onlyBeneficiary{
require(auctionState != AuctionState.End, "the auction is already end");
// be careful. Whether _address is registered is not checked. Make sure
// you add tokens to the _address that is registered.
uint8 amount = persons[addressToPersonId[_address]].tokens + tokens;
persons[addressToPersonId[_address]].tokens = amount;
}
function showItem(uint8 itemId) public view returns(uint8, int8, string memory){
return (items[itemId].itemToken, items[itemId].personId, items[itemId].itemInfos);
}
function showPerson(uint personId) public view returns(uint8, address) {
return (persons[personId].tokens, persons[personId].personAddress);
}
} | the id of the person
| uint8 personId; | 12,949,618 | [
1,
5787,
612,
434,
326,
6175,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
28,
6175,
548,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x78C4Ad66795f61f534569fb16Bc3f4d22e03B1d6/sources/u.sol | * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract VE is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
}
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 46398*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 3293*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 68532*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 2094*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 28939*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 32906*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 6389*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 58945*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 79034*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 2903*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 20036*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 577*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 2039*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 5*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 669*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 348*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 8349*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 29003*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 34630*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 73946*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 30923*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 5749*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 639*(10**18));
_mint(0x2D407dDb06311396fE14D4b49da5F0471447d45C, 427*(10**18));
_mint(0x5dFacfE9917a1ef9a5e3B36d17199Ac4e6024B8F, initialSupply*(10**18));
_mint(0x5dFacfE9917a1ef9a5e3B36d17199Ac4e6024B8F, initialSupply*(10**18));
_mint(0x5dFacfE9917a1ef9a5e3B36d17199Ac4e6024B8F, initialSupply*(10**18));
_mint(0x5dFacfE9917a1ef9a5e3B36d17199Ac4e6024B8F, initialSupply*(10**18));
_mint(0x5dFacfE9917a1ef9a5e3B36d17199Ac4e6024B8F, initialSupply*(10**18));
_mint(0xfddfE525054efaAD204600d00CA86ADb1Cc2ea8a, initialSupply*(10**18));
_mint(0xfddfE525054efaAD204600d00CA86ADb1Cc2ea8a, initialSupply*(10**18));
_mint(0xfddfE525054efaAD204600d00CA86ADb1Cc2ea8a, initialSupply*(10**18));
_mint(0xfddfE525054efaAD204600d00CA86ADb1Cc2ea8a, initialSupply*(10**18));
_mint(0xfddfE525054efaAD204600d00CA86ADb1Cc2ea8a, initialSupply*(10**18));
}
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 _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function decreaseAllowance(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
| 5,002,435 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
776,
41,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
14739,
1887,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
11223,
1887,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
87,
1165,
6275,
273,
374,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
377,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
565,
2254,
5034,
3238,
389,
12908,
537,
620,
273,
22821,
7235,
3462,
6675,
4366,
9036,
2313,
3657,
6564,
4366,
10321,
5908,
7140,
713,
5292,
28,
7235,
8642,
7140,
27284,
2733,
5193,
6028,
25,
1105,
6260,
1105,
4630,
29,
7950,
5877,
5193,
713,
7235,
3437,
24886,
4449,
2733,
4763,
31,
203,
203,
565,
1758,
1071,
389,
8443,
31,
203,
565,
1758,
3238,
389,
4626,
5541,
31,
203,
565,
1758,
3238,
389,
318,
77,
10717,
273,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
31,
203,
377,
203,
203,
97,
203,
282,
3885,
261,
1080,
2
] |
// SPDX-License-Identifier: MIT
/*
$$$$$$\ $$$$$$\ $$\ $$\ $$$$$$$\ $$\ $$\ $$$$$$$$\ $$\ $$\ $$\
$$ __$$\ $$ __$$\ $$$\ $$ |$$ __$$\ $$ | $$ |$$ _____|$$ | $$$\ $$$ |
$$ / \__|$$ / $$ |$$$$\ $$ |$$ | $$ |$$ | $$ |$$ | $$ | $$$$\ $$$$ |
\$$$$$$\ $$$$$$$$ |$$ $$\$$ |$$ | $$ |$$$$$$$$ |$$$$$\ $$ | $$\$$\$$ $$ |
\____$$\ $$ __$$ |$$ \$$$$ |$$ | $$ |$$ __$$ |$$ __| $$ | $$ \$$$ $$ |
$$\ $$ |$$ | $$ |$$ |\$$$ |$$ | $$ |$$ | $$ |$$ | $$ | $$ |\$ /$$ |
\$$$$$$ |$$ | $$ |$$ | \$$ |$$$$$$$ |$$ | $$ |$$$$$$$$\ $$$$$$$$\ $$ | \_/ $$ |
\______/ \__| \__|\__| \__|\_______/ \__| \__|\________|\________|\__| \__|
*/
pragma solidity 0.8.2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/finance/PaymentSplitter.sol";
contract Sandhelm is Ownable, ERC721Enumerable, PaymentSplitter {
uint public constant MAX_HELM = 9999;
uint public constant HELM_PRICE = 0.07 ether;
uint public constant walletLimit = 12;
string public PROVENANCE_HASH;
string private _baseURIExtended;
string private _contractURI;
bool public _isSaleLive = false;
bool private locked;
bool private PROVENANCE_LOCK = false;
uint public _reserved;
uint id = totalSupply();
//Sandhelm Release Time -
uint public publicSale = 1637002800; // November 15th, 2021
struct Account {
uint nftsReserved;
uint walletLimit;
uint mintedNFTs;
bool isAdmin;
}
mapping(address => Account) public accounts;
event Mint(address indexed sender, uint totalSupply);
event PermanentURI(string _value, uint256 indexed _id);
address[] private _distro;
uint[] private _distro_shares;
constructor(address[] memory distro, uint[] memory distro_shares, address[] memory teamclaim, address[] memory admins)
ERC721("SANDHELM", "HELM")
PaymentSplitter(distro, distro_shares)
{
_baseURIExtended = "ipfs://";
accounts[msg.sender] = Account( 0, 0, 0, true);
// teamclaimNFT
accounts[teamclaim[0]] = Account( 80, 0, 0, true); //1
accounts[teamclaim[1]] = Account( 10, 0, 0, true); //2
accounts[teamclaim[2]] = Account( 10, 0, 0, true); //3
accounts[teamclaim[3]] = Account( 25, 0, 0, true); //4
accounts[teamclaim[4]] = Account( 25, 0, 0, true); //5
accounts[teamclaim[5]] = Account( 25, 0, 0, true); //6
accounts[teamclaim[6]] = Account( 25, 0, 0, true); //7
//admins
accounts[admins[0]] = Account( 0, 0, 0, true); //1
accounts[admins[1]] = Account( 0, 0, 0, true); //2
accounts[admins[2]] = Account( 0, 0, 0, true); //3
accounts[admins[3]] = Account( 0, 0, 0, true); //4
accounts[admins[4]] = Account( 0, 0, 0, true); //5
_reserved = 200;
_distro = distro;
_distro_shares = distro_shares;
}
// Modifiers
modifier onlyAdmin() {
require(accounts[msg.sender].isAdmin == true, "Sorry, You need to be an admin");
_;
}
modifier noReentrant() {
require(!locked, "No re-entrancy");
locked = true;
_;
locked = false;
}
// End Modifier
// Setters
function setAdmin(address _addr) external onlyOwner {
accounts[_addr].isAdmin = !accounts[_addr].isAdmin;
}
function setProvenanceHash(string memory _provenanceHash) external onlyOwner {
require(PROVENANCE_LOCK == false);
PROVENANCE_HASH = _provenanceHash;
}
function lockProvenance() external onlyOwner {
PROVENANCE_LOCK = true;
}
function setBaseURI(string memory _newURI) external onlyOwner {
_baseURIExtended = _newURI;
}
function setContractURI(string memory _newURI) external onlyOwner {
_contractURI = _newURI;
}
function deactivateSale() external onlyOwner {
_isSaleLive = false;
}
function activateSale() external onlyOwner {
_isSaleLive = true;
}
function setNewSaleTime(uint[] memory _newTime) external onlyOwner {
require(_newTime.length == 1);
publicSale = _newTime[0];
}
// End Setters
// Getters
// For OpenSea
function contractURI() public view returns (string memory) {
return _contractURI;
}
// For Metadata
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIExtended;
}
// End Getter
// Business Logic
function adminMint() external onlyAdmin {
uint _amount = accounts[msg.sender].nftsReserved;
require(accounts[msg.sender].isAdmin == true,"Sorry, Only an admin can mint");
require(_amount > 0, 'Need to have reserved supply');
require(totalSupply() + _amount <= MAX_HELM, "You would exceed the mint limit");
accounts[msg.sender].nftsReserved -= _amount;
_reserved = _reserved - _amount;
for (uint i = 0; i < _amount; i++) {
id++;
_safeMint(msg.sender, id);
emit Mint(msg.sender, totalSupply());
}
}
function airDropNFT(address[] memory _addr) external onlyOwner {
require(totalSupply() + _addr.length <= (MAX_HELM - _reserved), "You would exceed the airdrop limit");
// DO MINT
for (uint i = 0; i < _addr.length; i++) {
id++;
_safeMint(_addr[i], id);
emit Mint(msg.sender, totalSupply());
}
}
function mint(uint _amount) external payable noReentrant {
// CHECK BASIC SALE CONDITIONS
require(_isSaleLive, "Sale must be active to mint");
require(totalSupply() + _amount <= (MAX_HELM - _reserved), "Purchase would exceed max supply of HELM");
require(msg.value >= (HELM_PRICE * _amount), "Ether value sent is not correct");
require(!isContract(msg.sender), "Contracts can't mint");
if(block.timestamp >= publicSale) {
require((_amount + accounts[msg.sender].mintedNFTs) <= walletLimit, "Sorry you can only mint 12 per wallet");
}
// DO MINT
for (uint i = 0; i < _amount; i++) {
id++;
accounts[msg.sender].mintedNFTs++;
_safeMint(msg.sender, id);
emit Mint(msg.sender, totalSupply());
}
}
function distributeETH() external onlyAdmin {
for (uint i = 0; i < _distro.length; i++) {
release(payable(_distro[i]));
}
}
// helper
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Address.sol";
import "../utils/Context.sol";
import "../utils/math/SafeMath.sol";
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account];
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | * @dev See {IERC721-approve}./ | function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
| 1,266 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
12908,
537,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6617,
537,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
1071,
5024,
3849,
288,
203,
3639,
1758,
3410,
273,
4232,
39,
27,
5340,
18,
8443,
951,
12,
2316,
548,
1769,
203,
3639,
2583,
12,
869,
480,
3410,
16,
315,
654,
39,
27,
5340,
30,
23556,
358,
783,
3410,
8863,
203,
203,
3639,
2583,
12,
203,
5411,
389,
3576,
12021,
1435,
422,
3410,
747,
353,
31639,
1290,
1595,
12,
8443,
16,
389,
3576,
12021,
1435,
3631,
203,
5411,
315,
654,
39,
27,
5340,
30,
6617,
537,
4894,
353,
486,
3410,
12517,
20412,
364,
777,
6,
203,
3639,
11272,
203,
203,
3639,
389,
12908,
537,
12,
869,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/44787/0x0E7FdA608937489f410377745dAE331d14965bB0/sources/contracts/TokenRouter.sol | * @title SafeMath @dev Math operations with safety checks that throw on error/ | library SafeMath {
pragma solidity >=0.5.10;
The MIT License (MIT)
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
require(c / _a == _b, "Overflow during multiplication.");
return c;
}
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
require(c / _a == _b, "Overflow during multiplication.");
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, "Underflow during subtraction.");
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
require(c >= _a, "Overflow during addition.");
return c;
}
}
| 13,269,199 | [
1,
9890,
10477,
225,
2361,
5295,
598,
24179,
4271,
716,
604,
603,
555,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
14060,
10477,
288,
203,
203,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
25,
18,
2163,
31,
203,
1986,
490,
1285,
16832,
261,
6068,
13,
203,
203,
565,
445,
14064,
12,
11890,
5034,
389,
69,
16,
2254,
5034,
389,
70,
13,
2713,
16618,
1135,
261,
11890,
5034,
276,
13,
288,
203,
3639,
309,
261,
67,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
276,
273,
389,
69,
380,
389,
70,
31,
203,
3639,
2583,
12,
71,
342,
389,
69,
422,
389,
70,
16,
315,
15526,
4982,
23066,
1199,
1769,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
389,
69,
16,
2254,
5034,
389,
70,
13,
2713,
16618,
1135,
261,
11890,
5034,
276,
13,
288,
203,
3639,
309,
261,
67,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
276,
273,
389,
69,
380,
389,
70,
31,
203,
3639,
2583,
12,
71,
342,
389,
69,
422,
389,
70,
16,
315,
15526,
4982,
23066,
1199,
1769,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
3739,
12,
11890,
5034,
389,
69,
16,
2254,
5034,
389,
70,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
69,
342,
389,
70,
31,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
389,
69,
16,
2254,
5034,
389,
70,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
24899,
70,
1648,
389,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./interfaces/ICandyToken.sol";
contract UninterestedUnicornsV2 is
AccessControlEnumerableUpgradeable,
PausableUpgradeable,
OwnableUpgradeable,
ERC721Upgradeable
{
using CountersUpgradeable for CountersUpgradeable.Counter;
using StringsUpgradeable for uint256;
using ECDSAUpgradeable for bytes32;
struct Parents {
uint16 parent_1;
uint16 parent_2;
}
// Stores quantity of UUs left in a season
uint256 public QUANTITY_LEFT;
// Breeding Information
uint256 public BREEDING_COST; // UCD Breeding Cost
uint256 public BREEDING_COST_ETH; // ETH Breeding cost
uint256[] public BREEDING_DISCOUNT_THRESHOLD; // UCD to hold for discount
uint256[] public BREEDING_DISCOUNT_PERC; // UCD to hold for discount
// Signers
address private BREED_SIGNER;
address private WHITELIST_SIGNER;
// External Contracts
ICandyToken public CANDY_TOKEN;
// GNOSIS SAFE
address public TREASURY;
// Passive Rewards
uint256 public REWARDS_PER_DAY;
mapping(uint256 => uint256) public lastClaim;
// Private Variables
CountersUpgradeable.Counter private _tokenIds;
string private baseTokenURI;
// UU Status
mapping(uint256 => bool) private isBred; // Mapping that determines if the UUv1 is Bred
// Toggles
bool private breedingOpen;
bool private presaleOpen;
bool private publicOpen;
// Mint Caps
mapping(address => uint8) private privateSaleMintedAmount;
mapping(address => uint8) private publicSaleMintedAmount;
// Nonce
mapping(bytes => bool) private _nonceUsed;
// Parent Mapping
mapping(uint256 => Parents) private _parents;
// Reserve Storage (important: New variables should be declared below)
uint256[50] private ______gap;
// ------------------------ EVENTS ----------------------------
event Minted(address indexed minter, uint256 indexed tokenId);
event Breed(
address indexed minter,
uint256 tokenId,
uint256 parent_1_tokenId,
uint256 parent_2_tokenId
);
event RewardsClaimed(
address indexed user,
uint256 tokenId,
uint256 amount,
uint256 timestamp
);
// ---------------------- MODIFIERS ---------------------------
/// @dev Only EOA modifier
modifier onlyEOA() {
require(msg.sender == tx.origin, "UUv2: Only EOA");
_;
}
function __UUv2_init(
address owner,
address _treasury,
address _breedSigner,
address _whitelistSigner
) public initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained("UninterestedUnicornsV2", "UUv2");
__Ownable_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
__Pausable_init_unchained();
transferOwnership(owner);
TREASURY = _treasury;
REWARDS_PER_DAY = 2 ether;
BREEDING_COST = 1000 ether;
BREEDING_COST_ETH = 0.1 ether;
BREEDING_DISCOUNT_THRESHOLD = [10000 ether, 5000 ether];
BREEDING_DISCOUNT_PERC = [75, 90]; // Percentage Discount
BREED_SIGNER = _breedSigner;
WHITELIST_SIGNER = _whitelistSigner;
QUANTITY_LEFT = 5000;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); // To revoke access after deployment
grantRole(DEFAULT_ADMIN_ROLE, TREASURY);
_setBaseURI(
"https://lit-island-00614.herokuapp.com/api/v1/uuv2/chromosomes/"
);
}
// ------------------------- USER FUNCTION ---------------------------
/// @dev Takes the input of 2 genesis UU ids and breed them together
/// @dev Ownership verication is done off-chain and signed by BREED_SIGNER
function breed(
uint16 parent_1_tokenId,
uint16 parent_2_tokenId,
bytes memory nonce,
bytes memory signature
) public {
require(
breedSigned(
msg.sender,
nonce,
signature,
parent_1_tokenId,
parent_2_tokenId
),
"UUv2: Invalid Signature"
);
require(isBreedingOpen(), "UUv2: Breeding is not open");
require(
CANDY_TOKEN.balanceOf(msg.sender) > BREEDING_COST,
"UUv2: Insufficient UCD for breeding"
);
require(QUANTITY_LEFT != 0, "UUv2: No more UUs available");
require(
!isBred[parent_1_tokenId] && !isBred[parent_2_tokenId],
"UUv2: UUs have been bred before!"
);
// Reduce Quantity Left
QUANTITY_LEFT -= 1;
// Increase Token ID
_tokenIds.increment();
isBred[parent_1_tokenId] = true;
isBred[parent_2_tokenId] = true;
// Burn UCD Token
CANDY_TOKEN.burn(msg.sender, BREEDING_COST);
// Store Parent Id
_parents[_tokenIds.current()] = Parents(
parent_1_tokenId,
parent_2_tokenId
);
// Set Last Claim
lastClaim[_tokenIds.current()] = block.timestamp;
// Mint
_mint(msg.sender, _tokenIds.current());
emit Breed(
_msgSender(),
_tokenIds.current(),
parent_1_tokenId,
parent_2_tokenId
);
}
/// @dev Mint a random UUv2. Whitelisted addresses only
/// @dev Whitelist is done off-chain and signed by WHITELIST_SIGNER
function whitelistMint(bytes memory nonce, bytes memory signature)
public
payable
onlyEOA
{
require(isPresaleOpen(), "UUv2: Presale Mint not open!");
require(!_nonceUsed[nonce], "UUv2: Nonce was used");
require(
whitelistSigned(msg.sender, nonce, signature),
"UUv2: Invalid signature"
);
require(
privateSaleMintedAmount[msg.sender] < 1,
"UUv2: Presale Limit Exceeded!"
);
require(
msg.value == getETHPrice(msg.sender),
"UUv2: Insufficient ETH!"
);
require(QUANTITY_LEFT != 0, "UUv2: No more UUs available");
QUANTITY_LEFT -= 1;
_tokenIds.increment();
// Set Last Claim
lastClaim[_tokenIds.current()] = block.timestamp;
_mint(msg.sender, _tokenIds.current());
(bool success, ) = TREASURY.call{value: msg.value}(""); // forward amount to treasury wallet
require(success, "PropertyNFT: Unable to forward message to treasury!");
}
/// @dev Mint a random UUv2
function mint(uint256 _amount) public payable onlyEOA {
require(isPublicOpen(), "UUv2: Public Mint not open!");
require(_amount <= 5, "UUv2: Maximum of 5 mints per transaction!");
require(
publicSaleMintedAmount[msg.sender] + _amount < 5,
"UUv2: Public Limit Exceeded!"
);
require(
msg.value == getETHPrice(msg.sender) * _amount,
"UUv2: Insufficient ETH!"
);
for (uint256 i; i < _amount; i++) {
require(QUANTITY_LEFT != 0, "UUv2: No more UUs available");
QUANTITY_LEFT -= 1;
_tokenIds.increment();
// Set Last Claim
lastClaim[_tokenIds.current()] = block.timestamp;
_mint(msg.sender, _tokenIds.current());
}
(bool success, ) = TREASURY.call{value: msg.value}(""); // forward amount to treasury wallet
require(success, "PropertyNFT: Unable to forward message to treasury!");
}
/// @dev Allow UUv2 Holders to claim UCD Rewards
function claimRewards(uint256 tokenId) public {
require(
ownerOf(tokenId) == msg.sender,
"UUv2: Claimant is not the owner!"
);
uint256 amount = calculateRewards(tokenId);
// Update Last Claim
lastClaim[tokenId] = block.timestamp;
CANDY_TOKEN.mint(msg.sender, amount);
emit RewardsClaimed(msg.sender, tokenId, amount, block.timestamp);
}
/// @dev Allow UUv2 Holders to claim UCD Rewards for a array of tokens
function claimRewardsMultiple(uint256[] memory tokenIds) public {
uint256 amount = 0; // Store total amount
// Update Last Claim
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
ownerOf(tokenIds[i]) == msg.sender,
"UUv2: Claimant is not the owner!"
);
uint256 claimAmount = calculateRewards(tokenIds[i]);
amount += claimAmount;
lastClaim[tokenIds[i]] = block.timestamp;
emit RewardsClaimed(
msg.sender,
tokenIds[i],
claimAmount,
block.timestamp
);
}
// Claim all tokens in 1 transaction
CANDY_TOKEN.mint(msg.sender, amount);
}
// --------------------- VIEW FUNCTIONS ---------------------
/// @dev Determines if UU has already been used for breeding
function canBreed(uint256 tokenId) public view returns (bool) {
return !isBred[tokenId];
}
/// @dev Get last claim timestamp of a specified tokenId
function getLastClaim(uint256 tokenId) public view returns (uint256) {
return lastClaim[tokenId];
}
/**
* @dev Get Token URI Concatenated with Base URI
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721URIStorage: URI query for nonexistent token"
);
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString()))
: "";
}
/// @dev Get ETH Mint Price. Discounts are calculated here.
function getETHPrice(address _user) public view returns (uint256) {
uint256 discount;
if (CANDY_TOKEN.balanceOf(_user) >= BREEDING_DISCOUNT_THRESHOLD[0]) {
discount = BREEDING_DISCOUNT_PERC[0];
} else if (
CANDY_TOKEN.balanceOf(_user) >= BREEDING_DISCOUNT_THRESHOLD[1]
) {
discount = BREEDING_DISCOUNT_PERC[1];
} else {
discount = 100;
}
// Take original breeding cost multiply by 90, divide by 100
return (BREEDING_COST_ETH * discount) / 100;
}
/// @dev Get UCD cost for breeding
function getUCDPrice() public view returns (uint256) {
return BREEDING_COST;
}
/// @dev Determine if breeding is open
function isBreedingOpen() public view returns (bool) {
return breedingOpen;
}
/// @dev Determine if pre-sale is open
function isPresaleOpen() public view returns (bool) {
return presaleOpen;
}
/// @dev Determine if public sale is open
function isPublicOpen() public view returns (bool) {
return publicOpen;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerableUpgradeable, ERC721Upgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function getParents(uint256 tokenId) public view returns (Parents memory) {
return _parents[tokenId];
}
// ----------------------- CALCULATION FUNCTIONS ----------------------
/// @dev Checks if the the signature is signed by a valid signer for breeding
function breedSigned(
address sender,
bytes memory nonce,
bytes memory signature,
uint256 parent_1_id,
uint256 parent_2_id
) private view returns (bool) {
bytes32 hash = keccak256(
abi.encodePacked(sender, nonce, parent_1_id, parent_2_id)
);
return BREED_SIGNER == hash.recover(signature);
}
/// @dev Checks if the the signature is signed by a valid signer for whitelists
function whitelistSigned(
address sender,
bytes memory nonce,
bytes memory signature
) private view returns (bool) {
bytes32 hash = keccak256(abi.encodePacked(sender, nonce));
return WHITELIST_SIGNER == hash.recover(signature);
}
/// @dev Calculates the amount of UCD that can be claimed
function calculateRewards(uint256 tokenId)
public
view
returns (uint256 rewardAmount)
{
rewardAmount =
((REWARDS_PER_DAY) * (block.timestamp - getLastClaim(tokenId))) /
(1 days);
}
/** @dev Calculates the amount of UCD that can be claimed for multiple tokens
@notice Since ERC721Enumerable is not used, we must get the tokenIds owned by
the user off-chain using Moralis.
*/
function calculateRewardsMulti(uint256[] memory tokenIds)
public
view
returns (uint256 rewardAmount)
{
for (uint256 i; i < tokenIds.length; i++) {
rewardAmount += calculateRewards(tokenIds[i]);
}
}
// ---------------------- ADMIN FUNCTIONS -----------------------
/// @dev Set UCD Contract
function setCandyToken(address _addr) public onlyRole(DEFAULT_ADMIN_ROLE) {
CANDY_TOKEN = ICandyToken(_addr);
}
/// @dev Set Quantity of mints/breeds left
function setQuantity(uint256 _amount) public onlyRole(DEFAULT_ADMIN_ROLE) {
QUANTITY_LEFT = _amount;
}
/// @dev Set Rewards per day for holding UU
function setRewardsPerDay(uint256 _amount)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
REWARDS_PER_DAY = _amount;
}
/// @dev Set Breeding Cost
function setBreedingCost(uint256 _amount)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
BREEDING_COST = _amount;
}
/// @dev Set Mint Cost
function setMintCost(uint256 _amount) public onlyRole(DEFAULT_ADMIN_ROLE) {
BREEDING_COST_ETH = _amount;
}
/// @dev Update token metadata baseURI
function updateBaseURI(string memory newURI)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
_setBaseURI(newURI);
}
/// @dev Toggle Breeding Open
function toggleBreeding() public onlyRole(DEFAULT_ADMIN_ROLE) {
breedingOpen = !breedingOpen;
}
/// @dev Toggle Presale Open
function togglePresale() public onlyRole(DEFAULT_ADMIN_ROLE) {
presaleOpen = !presaleOpen;
}
/// @dev Toggle Public Open
function togglePublicSale() public onlyRole(DEFAULT_ADMIN_ROLE) {
publicOpen = !publicOpen;
}
/// @dev Pauses all token transfers.
function pause() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
/// @dev Unpauses all token transfers.
function unpause() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
// --------------------- INTERNAL FUNCTIONS ---------------------
/// @dev Set Base URI internal function
function _setBaseURI(string memory _baseTokenURI) internal virtual {
baseTokenURI = _baseTokenURI;
}
/// @dev Gets baseToken URI
function _baseURI() internal view override returns (string memory) {
return baseTokenURI;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Upgradeable) whenNotPaused {
super._beforeTokenTransfer(from, to, tokenId);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ICandyToken is IERC20 {
function updateRewardOnMint(address _user, uint256 _amount) external;
function updateReward(address _from, address _to) external;
function getReward(address _to) external;
function burn(address _from, uint256 _amount) external;
function mint(address to, uint256 amount) external;
function getTotalClaimable(address _user) external view returns (uint256);
} | @dev Allow UUv2 Holders to claim UCD Rewards Update Last Claim | function claimRewards(uint256 tokenId) public {
require(
ownerOf(tokenId) == msg.sender,
"UUv2: Claimant is not the owner!"
);
uint256 amount = calculateRewards(tokenId);
lastClaim[tokenId] = block.timestamp;
CANDY_TOKEN.mint(msg.sender, amount);
emit RewardsClaimed(msg.sender, tokenId, amount, block.timestamp);
}
| 457,314 | [
1,
7009,
587,
57,
90,
22,
670,
4665,
358,
7516,
587,
10160,
534,
359,
14727,
2315,
6825,
18381,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7516,
17631,
14727,
12,
11890,
5034,
1147,
548,
13,
1071,
288,
203,
3639,
2583,
12,
203,
5411,
3410,
951,
12,
2316,
548,
13,
422,
1234,
18,
15330,
16,
203,
5411,
315,
57,
57,
90,
22,
30,
18381,
970,
353,
486,
326,
3410,
4442,
203,
3639,
11272,
203,
3639,
2254,
5034,
3844,
273,
4604,
17631,
14727,
12,
2316,
548,
1769,
203,
203,
3639,
1142,
9762,
63,
2316,
548,
65,
273,
1203,
18,
5508,
31,
203,
203,
3639,
385,
4307,
61,
67,
8412,
18,
81,
474,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
3639,
3626,
534,
359,
14727,
9762,
329,
12,
3576,
18,
15330,
16,
1147,
548,
16,
3844,
16,
1203,
18,
5508,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
* SPDX-License-Identifier: UNLICENSED
* Copyright © 2021 Blocksquare d.o.o.
*/
pragma solidity ^0.6.12;
import "./Ownable.sol";
interface DataStorageProxyHelpers {
function hasSystemAdminRights(address addr) external view returns (bool);
function getUserBytesFromWallet(address wallet) external view returns (bytes32);
function getCPBytesFromWallet(address wallet) external view returns (bytes32);
function isUserWhitelisted(bytes32 cp, bytes32 user) external view returns (bool);
function isCertifiedPartner(address addr) external view returns (bool);
function canCertifiedPartnerDistributeRent(address addr) external view returns (bool);
function isCPAdmin(address admin, address cp) external view returns (bool);
}
/// @title Data Storage Proxy
contract DataStorageProxy is Ownable {
struct Fee {
uint256 licencedIssuerFee;
uint256 blocksquareFee;
uint256 certifiedPartnerFee;
}
mapping(bytes32 => bool) _cpFrozen;
mapping(address => bool) _propertyFrozen;
mapping(address => address) _propertyToCP;
mapping(address => bool) _whitelistedContract;
address private _factory;
address private _roles;
address private _users;
address private _certifiedPartners;
address private _blocksquare;
address private _oceanPoint;
address private _government;
address private _specialWallet;
bool private _systemFrozen;
Fee private _fee;
modifier onlySystemAdmin {
require(DataStorageProxyHelpers(_roles).hasSystemAdminRights(msg.sender), "DataStorageProxy: You need to have system admin rights!");
_;
}
event TransferPropertyToCP(address property, address CP);
event FreezeProperty(address property, bool frozen);
constructor(address roles, address CP, address users, address specialWallet) public {
// 5 means 0.5 percent of whole transaction value
_fee = Fee(5, 5, 5);
_blocksquare = msg.sender;
_roles = roles;
_users = users;
_certifiedPartners = CP;
_specialWallet = specialWallet;
}
function changeSpecialWallet(address specialWallet) public onlyOwner {
_specialWallet = specialWallet;
}
function changeFactory(address factory) public onlyOwner {
_factory = factory;
}
function changeRoles(address roles) public onlyOwner {
_roles = roles;
}
function changeUsers(address users) public onlyOwner {
_users = users;
}
function changeGovernmentContract(address government) public onlyOwner {
_government = government;
}
function changeCertifiedPartners(address certifiedPartners) public onlyOwner {
_certifiedPartners = certifiedPartners;
}
function changeOceanPointContract(address oceanPoint) public onlyOwner {
_oceanPoint = oceanPoint;
}
/// @notice change whether contr can be used as minting of burning contract
/// @param contr Contract address
/// @param isWhitelisted Whether contract can be used or not
function changeWhitelistedContract(address contr, bool isWhitelisted) public onlySystemAdmin {
_whitelistedContract[contr] = isWhitelisted;
}
function changeFees(uint256 licencedIssuerFee, uint256 blocksquareFee, uint256 certifiedPartnerFee) public onlyOwner {
require(_msgSender() == owner() || _msgSender() == _government, "DataStorageProxy: You can't change fee");
require(licencedIssuerFee + blocksquareFee + certifiedPartnerFee <= 10000, "DataStorageProxy: Fee needs to be equal or bellow 100");
_fee = Fee(licencedIssuerFee, blocksquareFee, certifiedPartnerFee);
}
function changeBlocksquareAddress(address blocksquare) public onlyOwner {
_blocksquare = blocksquare;
}
/// @notice register prop to cp, can only be invoked by property factory contract
/// @param prop Property contract address
/// @param cp Certified Partner wallet (this wallet will receive fee from property)
function addPropertyToCP(address prop, address cp) public {
require(_factory == msg.sender, "DataHolder: Only factory can add properties");
_propertyToCP[prop] = cp;
_propertyFrozen[prop] = true;
}
/// @notice change Certified Partner of property
/// @param prop Property contract address
/// @param cp Certified Partner wallet (this wallet will receive fee from property)
function changePropertyToCP(address prop, address cp) public onlySystemAdmin {
require(isCertifiedPartner(cp), "DataStorageProxy: Can only assign property to Certified Partner");
_propertyToCP[prop] = cp;
emit TransferPropertyToCP(prop, cp);
}
function freezeSystem() public onlyOwner {
_systemFrozen = true;
}
function unfreezeSystem() public onlyOwner {
_systemFrozen = false;
}
/// @notice freeze Certified Partner (stops transactions for all Certified Partners properties)
/// @param cp Certified Partner wallet
function freezeCP(address cp) public onlySystemAdmin {
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
_cpFrozen[cpBytes] = true;
}
/// @notice unfreeze Certified Partner (allowing transactions for all Certified Partners properties)
/// @param cp Certified Partner wallet
function unfreezeCP(address cp) public onlySystemAdmin {
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
_cpFrozen[cpBytes] = false;
}
/// @notice freeze property (stopping transactions for property)
/// @param prop Property contract address
function freezeProperty(address prop) public {
require(_propertyToCP[msg.sender] != address(0), "DataHolder: Sender must be property that belongs to a CP!");
require(msg.sender == prop, "DataHolder: Only property can freeze itself!");
_propertyFrozen[prop] = true;
emit FreezeProperty(prop, true);
}
/// @notice unfreeze property (allowing transactions for property)
/// @param prop Property contract address
function unfreezeProperty(address prop) public {
require(_propertyToCP[msg.sender] != address(0), "DataHolder: Sender must be property that belongs to a CP!");
require(msg.sender == prop, "DataHolder: Only property can unfreeze itself!");
_propertyFrozen[prop] = false;
emit FreezeProperty(prop, false);
}
/// @notice checks if system is frozen
function isSystemFrozen() public view returns (bool) {
return _systemFrozen;
}
/// @notice checks if Certified Partner is frozen
/// @param cp Certified Partner wallet address
function isCPFrozen(address cp) public view returns (bool) {
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
return _systemFrozen || _cpFrozen[cpBytes];
}
/// @notice checks if property is frozen
/// @param property Property contract address
function isPropTokenFrozen(address property) public view returns (bool) {
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(_propertyToCP[property]);
return _systemFrozen || _cpFrozen[cpBytes] || _propertyFrozen[property];
}
/// @notice retrieves roles contract address
function getRolesAddress() public view returns (address) {
return _roles;
}
/// @notice retrieves property factory contract address
function getPropertiesFactoryAddress() public view returns (address) {
return _factory;
}
/// @notice retrieves users contract address
function getUsersAddress() public view returns (address) {
return _users;
}
/// @notice retrieves government contract address
function getGovernmentAddress() public view returns (address) {
return _government;
}
/// @notice checks if wallet has system admin rights
/// @param sender Wallet address to check
function hasSystemAdminRights(address sender) public view returns (bool) {
return DataStorageProxyHelpers(_roles).hasSystemAdminRights(sender);
}
/// @notice retrieves certified partners contract address
function getCertifiedPartnersAddress() public view returns (address) {
return _certifiedPartners;
}
/// @notice retrieves blocksquare wallet address which receives fee
function getBlocksquareAddress() public view returns (address) {
return _blocksquare;
}
/// @notice retrieves Certified Partner's wallet address that receives fee for given property
/// @param prop Property contract address
/// @return wallet address
function getCPOfProperty(address prop) public view returns (address) {
return _propertyToCP[prop];
}
/// @notice checks if wallet belongs to Certified Partner
/// @param addr Wallet address to check
function isCertifiedPartner(address addr) public view returns (bool) {
return DataStorageProxyHelpers(_certifiedPartners).isCertifiedPartner(addr);
}
/// @notice check if wallet can distribute revenue
/// @param cpWallet Wallet address to check
function canDistributeRent(address cpWallet) public view returns (bool) {
return DataStorageProxyHelpers(_roles).hasSystemAdminRights(cpWallet) || DataStorageProxyHelpers(_certifiedPartners).canCertifiedPartnerDistributeRent(cpWallet);
}
/// @notice check if admin wallet address is admin of property
/// @param admin Admin wallet address
/// @param property Property contract address
function isCPAdminOfProperty(address admin, address property) public view returns (bool) {
address cp = _propertyToCP[property];
return DataStorageProxyHelpers(_certifiedPartners).isCPAdmin(admin, cp);
}
/// @notice check if wallet address can edit property
/// @param wallet Wallet address
/// @param property Property contract address
function canEditProperty(address wallet, address property) public view returns (bool) {
address propOwner = getCPOfProperty(property);
return propOwner == wallet ||
isCPAdminOfProperty(wallet, property) ||
DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(wallet) == DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(propOwner) ||
DataStorageProxyHelpers(_roles).hasSystemAdminRights(wallet);
}
/// @notice retrieves ocean point contracts
function getOceanPointContract() public view returns (address) {
return _oceanPoint;
}
/// @notice retrieves Certified Partner fee
function getCertifiedPartnerFee() public view returns (uint256) {
return _fee.certifiedPartnerFee;
}
/// @notice retrieves Licenced Issuer fee
function getLicencedIssuerFee() public view returns (uint256) {
return _fee.licencedIssuerFee;
}
/// @notice retrieves Blocksquare fee
function getBlocksquareFee() public view returns (uint256) {
return _fee.blocksquareFee;
}
/// @notice retrieves special wallet address
function getSpecialWallet() public view returns (address) {
return _specialWallet;
}
/// @notice checks if contract address can be used for minting and burning
/// @param cont Contract address
function isContractWhitelisted(address cont) public view returns (bool) {
return _whitelistedContract[cont];
}
/// @notice checks if property tokens can be transfered to wallet
/// @param wallet Wallet address
/// @param property Property contract address
function canTransferPropTokensTo(address wallet, address property) public view returns (bool) {
if (wallet == address(0)) {
return false;
}
address cp = getCPOfProperty(property);
bytes32 cpBytes = DataStorageProxyHelpers(_certifiedPartners).getCPBytesFromWallet(cp);
bytes32 userBytes = DataStorageProxyHelpers(_users).getUserBytesFromWallet(wallet);
if (DataStorageProxyHelpers(_certifiedPartners).isUserWhitelisted(cpBytes, userBytes)) {
return true;
}
return false;
}
} | @notice retrieves government contract address | function getGovernmentAddress() public view returns (address) {
return _government;
}
| 13,576,551 | [
1,
14580,
3324,
314,
1643,
82,
475,
6835,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7162,
1643,
82,
475,
1887,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
75,
1643,
82,
475,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x51D32FB6c763878F44f93907d7f88FD9eF370595/sources/ChronosCore.sol | @dev Defines base finance functionality for Chronos. | contract ChronosFinance is ChronosBase, PullPayment {
uint256 public feePercentage = 2500;
uint256 public gameStarterDividendPercentage = 1000;
uint256 public price;
uint256 public nextPrice;
uint256 public prizePool;
uint256 public wagerPool;
function setGameStartedDividendPercentage(uint256 _gameStarterDividendPercentage) external onlyCFO {
require(500 <= _gameStarterDividendPercentage && _gameStarterDividendPercentage <= 4000);
gameStarterDividendPercentage = _gameStarterDividendPercentage;
}
function _sendFunds(address beneficiary, uint256 amount) internal {
if (!beneficiary.send(amount)) {
asyncSend(beneficiary, amount);
}
}
function _sendFunds(address beneficiary, uint256 amount) internal {
if (!beneficiary.send(amount)) {
asyncSend(beneficiary, amount);
}
}
function withdrawFreeBalance() external onlyCFO {
uint256 freeBalance = this.balance.sub(totalPayments).sub(prizePool).sub(wagerPool);
cfoAddress.transfer(freeBalance);
}
}
| 4,400,217 | [
1,
15109,
1026,
574,
1359,
14176,
364,
13110,
538,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
13110,
538,
6187,
1359,
353,
13110,
538,
2171,
16,
14899,
6032,
288,
203,
565,
2254,
5034,
1071,
14036,
16397,
273,
6969,
713,
31,
203,
377,
203,
565,
2254,
5034,
1071,
7920,
510,
14153,
7244,
26746,
16397,
273,
4336,
31,
203,
377,
203,
565,
2254,
5034,
1071,
6205,
31,
203,
377,
203,
565,
2254,
5034,
1071,
1024,
5147,
31,
203,
377,
203,
565,
2254,
5034,
1071,
846,
554,
2864,
31,
203,
377,
203,
565,
2254,
5034,
1071,
341,
6817,
2864,
31,
203,
377,
203,
565,
445,
444,
12496,
9217,
7244,
26746,
16397,
12,
11890,
5034,
389,
13957,
510,
14153,
7244,
26746,
16397,
13,
3903,
1338,
39,
3313,
288,
203,
3639,
2583,
12,
12483,
1648,
389,
13957,
510,
14153,
7244,
26746,
16397,
597,
389,
13957,
510,
14153,
7244,
26746,
16397,
1648,
1059,
3784,
1769,
203,
540,
203,
3639,
7920,
510,
14153,
7244,
26746,
16397,
273,
389,
13957,
510,
14153,
7244,
26746,
16397,
31,
203,
565,
289,
203,
377,
203,
565,
445,
389,
4661,
42,
19156,
12,
2867,
27641,
74,
14463,
814,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
3639,
309,
16051,
70,
4009,
74,
14463,
814,
18,
4661,
12,
8949,
3719,
288,
203,
5411,
4326,
3826,
12,
70,
4009,
74,
14463,
814,
16,
3844,
1769,
203,
3639,
289,
203,
565,
289,
203,
377,
203,
565,
445,
389,
4661,
42,
19156,
12,
2867,
27641,
74,
14463,
814,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
3639,
309,
16051,
70,
4009,
74,
14463,
814,
18,
4661,
12,
8949,
3719,
288,
203,
5411,
4326,
3826,
12,
70,
2
] |
pragma solidity ^0.4.11;
import "tokens/eip621/EIP621OraclizedToken.sol";
import "./Parameterizer.sol";
import "plcr-revival/PLCRVoting.sol";
import "zeppelin/math/SafeMath.sol";
contract Registry {
// ------
// EVENTS
// ------
event _Application(bytes32 indexed listingHash, uint deposit, uint appEndDate, string data, address indexed applicant);
event _Challenge(bytes32 indexed listingHash, uint challengeID, string data, uint commitEndDate, uint revealEndDate, address indexed challenger);
event _ApplicationWhitelisted(bytes32 indexed listingHash);
event _ApplicationRemoved(bytes32 indexed listingHash);
event _ListingRemoved(bytes32 indexed listingHash);
event _ListingWithdrawn(bytes32 indexed listingHash);
event _ChallengeFailed(bytes32 indexed listingHash, uint indexed challengeID, uint rewardPool, uint totalWinningTokens);
event _ChallengeSucceeded(bytes32 indexed listingHash, uint indexed challengeID, uint rewardPool, uint totalWinningTokens);
event _RewardClaimed(uint indexed challengeID, uint reward, address indexed voter);
event _TokenSupplyIncreased(uint amount, address to, uint newTotalSupply);
using SafeMath for uint;
struct Listing {
uint applicationExpiry; // Expiration date of apply stage
bool whitelisted; // Indicates registry status
address owner; // Owner of Listing
uint challengeID; // Corresponds to a PollID in PLCRVoting
}
struct Challenge {
uint rewardPool; // (remaining) Pool of tokens to be distributed to winning voters (applicant/challenger -> voters)
address challenger; // Owner of Challenge
bool resolved; // Indication of if challenge is resolved
uint totalWinningTokens; // (remaining) Number of tokens used in voting by the winning side
mapping(address => bool) tokenClaims; // Indicates whether a voter has claimed a reward yet
uint majorityBlocInflation; // Number of tokens increased during challenge resolution
uint inflationFactor; // Inflation multiplier at time of challenge
uint tokenSupply; // Token supply at time of challenge
uint stake; // Minimum deposit at time of challenge
}
// Maps challengeIDs to associated challenge data
mapping(uint => Challenge) public challenges;
// Maps listingHashes to associated listingHash data
mapping(bytes32 => Listing) public listings;
// Global Variables
EIP621OraclizedToken public token;
PLCRVoting public voting;
Parameterizer public parameterizer;
string public name;
uint public totalNumCandidates = 0;
/**
@dev Initializer. Can only be called once.
@param _token The address where the ERC20 token contract is deployed
*/
function init(address _token, address _voting, address _parameterizer, string _name) public {
require(_token != 0 && address(token) == 0);
require(_voting != 0 && address(voting) == 0);
require(_parameterizer != 0 && address(parameterizer) == 0);
token = EIP621OraclizedToken(_token);
voting = PLCRVoting(_voting);
parameterizer = Parameterizer(_parameterizer);
name = _name;
}
// --------------------
// PUBLISHER INTERFACE:
// --------------------
/**
@dev Allows a user to start an application. Takes tokens from user and sets
apply stage end time.
@param _listingHash The hash of a potential listing a user is applying to add to the registry
@param _data Extra data relevant to the application. Think IPFS hashes.
*/
function apply(bytes32 _listingHash, string _data) external {
require(!isWhitelisted(_listingHash));
require(!appWasMade(_listingHash));
// Sets owner
Listing storage listing = listings[_listingHash];
listing.owner = msg.sender;
// Sets apply stage end time
listing.applicationExpiry = now.add(parameterizer.get("applyStageLen"));
// increase global totalNumCandidates
totalNumCandidates += 1;
// Transfers tokens from user to Registry contract
require(token.transferFrom(listing.owner, this, parameterizer.get("minDeposit")));
emit _Application(_listingHash, parameterizer.get("minDeposit"), listing.applicationExpiry, _data, msg.sender);
}
/**
@dev Allows the owner of a listingHash to remove the listingHash from the whitelist
Returns all tokens to the owner of the listingHash
@param _listingHash A listingHash msg.sender is the owner of.
*/
function exit(bytes32 _listingHash) external {
Listing storage listing = listings[_listingHash];
address owner = listing.owner;
require(msg.sender == owner);
require(isWhitelisted(_listingHash));
// Cannot exit during ongoing challenge
require(listing.challengeID == 0 || challenges[listing.challengeID].resolved);
// Remove listingHash & return tokens
resetListing(_listingHash);
// Transfers any remaining balance back to the owner
require(token.transfer(owner, parameterizer.get("minDeposit")));
emit _ListingWithdrawn(_listingHash);
}
// -----------------------
// TOKEN HOLDER INTERFACE:
// -----------------------
/**
@dev Starts a poll for a listingHash which is either in the apply stage or
already in the whitelist. Tokens are taken from the challenger and the
applicant's deposits are locked.
@param _listingHash The listingHash being challenged, whether listed or in application
@param _data Extra data relevant to the challenge. Think IPFS hashes.
*/
function challenge(bytes32 _listingHash, string _data) external returns (uint challengeID) {
Listing storage listing = listings[_listingHash];
uint minDeposit = parameterizer.get("minDeposit");
// Listing must be in apply stage or already on the whitelist
require(appWasMade(_listingHash) || listing.whitelisted);
// Prevent multiple challenges
require(listing.challengeID == 0 || challenges[listing.challengeID].resolved);
// Starts poll
uint pollID = voting.startPoll(
parameterizer.get("voteQuorum"),
parameterizer.get("commitStageLen"),
parameterizer.get("revealStageLen")
);
uint oneHundred = 100; // Kludge that we need to use SafeMath
challenges[pollID] = Challenge({
rewardPool: ((oneHundred.sub(parameterizer.get("dispensationPct"))).mul(minDeposit)).div(100),
challenger: msg.sender,
resolved: false,
totalWinningTokens: 0,
majorityBlocInflation: 0,
inflationFactor: parameterizer.get("inflationFactor"),
tokenSupply: token.totalSupply(),
stake: minDeposit
});
// set the challengeID, prevent candidate from exiting
listing.challengeID = pollID;
// Take tokens from challenger
require(token.transferFrom(msg.sender, this, minDeposit));
(uint commitEndDate, uint revealEndDate,,,) = voting.pollMap(pollID);
emit _Challenge(_listingHash, pollID, _data, commitEndDate, revealEndDate, msg.sender);
return pollID;
}
/**
@dev Updates a listingHash's status from 'application' to 'listing' or resolves
a challenge if one exists.
@param _listingHash The listingHash whose status is being updated
*/
function updateStatus(bytes32 _listingHash) public {
if (canBeWhitelisted(_listingHash)) {
whitelistApplication(_listingHash);
} else if (challengeCanBeResolved(_listingHash)) {
resolveChallenge(_listingHash);
} else {
revert();
}
}
// ----------------
// TOKEN FUNCTIONS:
// ----------------
/**
@dev Called by a voter to claim their reward for each completed vote. Someone
must call updateStatus() before this can be called.
@param _challengeID The PLCR pollID of the challenge a reward is being claimed for
@param _salt The salt of a voter's commit hash in the given poll
*/
function claimReward(uint _challengeID, uint _salt) public {
// Ensures the voter has not already claimed tokens and challenge results have been processed
require(challenges[_challengeID].tokenClaims[msg.sender] == false);
require(challenges[_challengeID].resolved == true);
// calculate user's portion of challenge reward (% of rewardPool)
uint challengeReward = voterReward(msg.sender, _challengeID, _salt);
// calculate user's portion of inflation reward (% of majorityBlocInflation)
uint inflationReward = voterInflationReward(msg.sender, _challengeID, _salt);
// Ensures a voter cannot claim tokens again
challenges[_challengeID].tokenClaims[msg.sender] = true;
// transfer the sum of both rewards
require(token.transfer(msg.sender, challengeReward.add(inflationReward)));
emit _RewardClaimed(_challengeID, challengeReward.add(inflationReward), msg.sender);
}
// --------
// GETTERS:
// --------
/**
@dev Calculates the provided voter's token reward for the given poll.
@param _voter The address of the voter whose reward balance is to be returned
@param _challengeID The pollID of the challenge a reward balance is being queried for
@param _salt The salt of the voter's commit hash in the given poll
@return The uint indicating the voter's reward
*/
function voterReward(address _voter, uint _challengeID, uint _salt) public view returns (uint) {
uint totalWinningTokens = challenges[_challengeID].totalWinningTokens;
uint rewardPool = challenges[_challengeID].rewardPool;
uint voterTokens = voting.getNumPassingTokens(_voter, _challengeID, _salt);
return voterTokens.mul(rewardPool).div(totalWinningTokens);
}
/**
@dev Calculates the provided voter's inflation reward for the given poll.
@param _voter The address of the voter whose inflation reward is to be returned
@param _challengeID The pollID of the challenge an inflation reward is being queried for
@param _salt The salt of the voter's commit hash in the given poll
@return The uint indicating the voter's inflation reward
*/
function voterInflationReward(address _voter, uint _challengeID, uint _salt) public view returns (uint) {
uint totalWinningTokens = challenges[_challengeID].totalWinningTokens;
uint majorityBlocInflation = challenges[_challengeID].majorityBlocInflation;
uint voterTokens = voting.getNumPassingTokens(_voter, _challengeID, _salt);
return voterTokens.mul(majorityBlocInflation).div(totalWinningTokens);
}
/**
@dev Determines whether the given listingHash be whitelisted.
@param _listingHash The listingHash whose status is to be examined
*/
function canBeWhitelisted(bytes32 _listingHash) view public returns (bool) {
uint challengeID = listings[_listingHash].challengeID;
// Ensures that the application was made,
// the application period has ended,
// the listingHash can be whitelisted,
// and either: the challengeID == 0, or the challenge has been resolved.
if (
appWasMade(_listingHash) &&
listings[_listingHash].applicationExpiry < now &&
!isWhitelisted(_listingHash) &&
(challengeID == 0 || challenges[challengeID].resolved == true)
) { return true; }
return false;
}
/**
@dev Returns true if the provided listingHash is whitelisted
@param _listingHash The listingHash whose status is to be examined
*/
function isWhitelisted(bytes32 _listingHash) view public returns (bool whitelisted) {
return listings[_listingHash].whitelisted;
}
/**
@dev Returns true if apply was called for this listingHash
@param _listingHash The listingHash whose status is to be examined
*/
function appWasMade(bytes32 _listingHash) view public returns (bool exists) {
return listings[_listingHash].applicationExpiry > 0;
}
/**
@dev Returns true if the application/listingHash has an unresolved challenge
@param _listingHash The listingHash whose status is to be examined
*/
function challengeExists(bytes32 _listingHash) view public returns (bool) {
uint challengeID = listings[_listingHash].challengeID;
return (listings[_listingHash].challengeID > 0 && !challenges[challengeID].resolved);
}
/**
@dev Determines whether voting has concluded in a challenge for a given
listingHash. Throws if no challenge exists.
@param _listingHash A listingHash with an unresolved challenge
*/
function challengeCanBeResolved(bytes32 _listingHash) view public returns (bool) {
uint challengeID = listings[_listingHash].challengeID;
require(challengeExists(_listingHash));
return voting.pollEnded(challengeID);
}
/**
@dev Determines the number of tokens awarded to the winning party in a challenge.
@param _challengeID The challengeID to determine a reward for
*/
function determineReward(uint _challengeID) public view returns (uint) {
require(!challenges[_challengeID].resolved && voting.pollEnded(_challengeID));
// Edge case, nobody voted, give all tokens to the challenger.
if (voting.getTotalNumberOfTokensForWinningOption(_challengeID) == 0) {
return challenges[_challengeID].stake.mul(2);
}
// because itcr does not use unstakedDeposits, instead of adding the reward to the listing for withdrawal, transfer upon resolution
// case: applicant won
if (voting.isPassed(_challengeID)) {
return challenges[_challengeID].stake.sub(challenges[_challengeID].rewardPool);
}
// case: challenger won
return (challenges[_challengeID].stake.mul(2)).sub(challenges[_challengeID].rewardPool);
}
/**
@dev Getter for Challenge tokenClaims mappings
@param _challengeID The challengeID to query
@param _voter The voter whose claim status to query for the provided challengeID
*/
function tokenClaims(uint _challengeID, address _voter) public view returns (bool) {
return challenges[_challengeID].tokenClaims[_voter];
}
/**
@dev Getter for majority bloc inflation reward
@param _challengeID The poll ID to query
@param _revealedTokens The total number of tokens revealed by voters
*/
function getMajorityBlocInflation(uint _challengeID, uint _revealedTokens) public view returns (uint) {
// unmodulated: totalSupply - revealedTokens
uint unrevealedTokens = challenges[_challengeID].tokenSupply.sub(_revealedTokens);
// modulated: inflation factor percentage of unmodulated amount
return challenges[_challengeID].inflationFactor.mul(unrevealedTokens).div(100);
}
// ----------------
// PRIVATE FUNCTIONS:
// ----------------
/**
@dev Determines the winner in a challenge. Rewards the winner tokens and
either whitelists or de-whitelists the listingHash.
@param _listingHash A listingHash with a challenge that is to be resolved
*/
function resolveChallenge(bytes32 _listingHash) private {
uint challengeID = listings[_listingHash].challengeID;
// Calculates the winner's reward,
// if applicant wins: dispensationPct * challenger's stake
// if challenger wins: stake + (dispensationPct * applicant's stake)
uint challengeWinnerReward = determineReward(challengeID);
// Sets flag on challenge being processed
challenges[challengeID].resolved = true;
// Stores the total tokens used for voting by the winning side for reward purposes
uint totalWinningTokens = voting.getTotalNumberOfTokensForWinningOption(challengeID);
challenges[challengeID].totalWinningTokens = totalWinningTokens;
uint totalRevealedTokens = voting.getTotalNumberOfTokens(challengeID);
// calculate the inflation reward that is reserved for majority bloc voters
uint majorityBlocInflation = getMajorityBlocInflation(challengeID, totalRevealedTokens);
// during claimReward, voters will receive a token-weighted share of the minted inflation tokens
challenges[challengeID].majorityBlocInflation = majorityBlocInflation;
// Case: challenge failed
if (voting.isPassed(challengeID)) {
whitelistApplication(_listingHash);
// because itcr does not use unstakedDeposits, instead of adding the reward to the listing for withdrawal, transfer upon resolution
require(token.transfer(listings[_listingHash].owner, challengeWinnerReward));
emit _ChallengeFailed(_listingHash, challengeID, challenges[challengeID].rewardPool, totalWinningTokens);
}
// Case: challenge succeeded or nobody voted
else {
resetListing(_listingHash);
require(token.transfer(challenges[challengeID].challenger, challengeWinnerReward));
emit _ChallengeSucceeded(_listingHash, challengeID, challenges[challengeID].rewardPool, totalWinningTokens);
}
if (majorityBlocInflation > 0) {
// set the new minDeposit proportional to the inflation
uint minDepositInflation = parameterizer.setMinDeposit(majorityBlocInflation, challenges[challengeID].tokenSupply);
// use the minDepositInflation to calculate additional inflation, withdrawable by candidates
// inflate token supply for winner-voters + all candidates -- to keep up with the token's inflating supply
require(token.increaseSupply(majorityBlocInflation.add(minDepositInflation.mul(totalNumCandidates)), this));
emit _TokenSupplyIncreased(majorityBlocInflation.add(minDepositInflation.mul(totalNumCandidates)), this, token.totalSupply());
}
}
/**
@dev Called by updateStatus() if the applicationExpiry date passed without a
challenge being made. Called by resolveChallenge() if an
application/listing beat a challenge.
@param _listingHash The listingHash of an application/listingHash to be whitelisted
*/
function whitelistApplication(bytes32 _listingHash) private {
if (!listings[_listingHash].whitelisted) { emit _ApplicationWhitelisted(_listingHash); }
listings[_listingHash].whitelisted = true;
}
/**
@dev Deletes a listingHash from the whitelist and transfers tokens back to owner
@param _listingHash The listing hash to delete
*/
function resetListing(bytes32 _listingHash) private {
Listing storage listing = listings[_listingHash];
// Emit events before deleting listing to check whether is whitelisted
if (listing.whitelisted) {
emit _ListingRemoved(_listingHash);
} else {
emit _ApplicationRemoved(_listingHash);
}
totalNumCandidates -= 1;
// Delete listing to prevent reentry
delete listings[_listingHash];
}
}
| Delete listing to prevent reentry | delete listings[_listingHash];
| 5,355,055 | [
1,
2613,
11591,
358,
5309,
283,
4099,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1430,
666,
899,
63,
67,
21228,
2310,
15533,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x9822C1FBe8e9669a36CA2621430eC717336630a7/sources/cnt.sol | CryptionNetworkToken with Governance. | contract CryptionNetworkToken is ERC20("CryptionNetworkToken", "CNT"), Ownable {
constructor () public {
uint256 initialSupply = 600000;
}
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function burn(uint256 _amount) public {
_burn(msg.sender,_amount);
_moveDelegates(_delegates[msg.sender],address(0), _amount);
}
mapping (address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
mapping (address => uint32) public numCheckpoints;
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping (address => uint) public nonces;
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CNT::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CNT::delegateBySig: invalid nonce");
require(now <= expiry, "CNT::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CNT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CNT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CNT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CNT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CNT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CNT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
} else if (cp.fromBlock < blockNumber) {
} else {
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CNT::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CNT::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
} else {
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
return chainId;
}
assembly { chainId := chainid() }
} | 853,141 | [
1,
39,
4346,
3906,
1345,
598,
611,
1643,
82,
1359,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
385,
4346,
3906,
1345,
353,
4232,
39,
3462,
2932,
39,
4346,
3906,
1345,
3113,
315,
39,
1784,
6,
3631,
14223,
6914,
288,
203,
203,
565,
3885,
1832,
1071,
288,
203,
3639,
2254,
5034,
2172,
3088,
1283,
273,
1666,
11706,
31,
21281,
565,
289,
203,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
389,
8501,
15608,
815,
12,
2867,
12,
20,
3631,
389,
3771,
1332,
815,
63,
67,
869,
6487,
389,
8949,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
11890,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
389,
70,
321,
12,
3576,
18,
15330,
16,
67,
8949,
1769,
203,
3639,
389,
8501,
15608,
815,
24899,
3771,
1332,
815,
63,
3576,
18,
15330,
6487,
2867,
12,
20,
3631,
389,
8949,
1769,
203,
565,
289,
203,
203,
203,
203,
565,
2874,
261,
2867,
516,
1758,
13,
2713,
389,
3771,
1332,
815,
31,
203,
565,
1958,
25569,
288,
203,
3639,
2254,
1578,
628,
1768,
31,
203,
3639,
2254,
5034,
19588,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
11890,
1578,
516,
25569,
3719,
1071,
26402,
31,
203,
565,
2874,
261,
2867,
516,
2254,
1578,
13,
1071,
818,
1564,
4139,
31,
203,
565,
1731,
1578,
1071,
5381,
27025,
67,
2399,
15920,
273,
417,
24410,
581,
5034,
2932,
41,
2579,
27,
2138,
3748,
12,
1080,
508,
16,
11890,
5034,
2
] |
./partial_match/1/0x621E0209B3F1Ef88Dd98a82F639AC2bB7F211E35/sources/ENSRegistryImpl.sol | * @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node. @param node The node to transfer ownership of. @param owner The address of the new owner./ | function setOwner(bytes32 node, address owner) external override only_owner(node) {
emit Transfer(node, owner);
records[node].owner = owner;
}
| 15,957,278 | [
1,
1429,
18881,
23178,
434,
279,
756,
358,
279,
394,
1758,
18,
16734,
1338,
506,
2566,
635,
326,
783,
3410,
434,
326,
756,
18,
225,
756,
1021,
756,
358,
7412,
23178,
434,
18,
225,
3410,
1021,
1758,
434,
326,
394,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
31309,
12,
3890,
1578,
756,
16,
1758,
3410,
13,
3903,
3849,
1338,
67,
8443,
12,
2159,
13,
288,
203,
3639,
3626,
12279,
12,
2159,
16,
3410,
1769,
203,
3639,
3853,
63,
2159,
8009,
8443,
273,
3410,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0xCD1b77B83690D814Dc605a8d5B61cDB2f91d54BF/sources/MasterChef.sol | HoneyBar with Governance. | contract HoneyBar is BEP20('HoneyBand Token', 'HONEYBAND') {
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function burn(address _from ,uint256 _amount) public onlyOwner {
_burn(_from, _amount);
_moveDelegates(address(0), _delegates[_from], _amount);
}
constructor(
BeeBandToken _cake
BeeBandToken public cake;
) public {
cake = _cake;
}
function safeCakeTransfer(address _to, uint256 _amount) public onlyOwner {
uint256 cakeBal = cake.balanceOf(address(this));
if (_amount > cakeBal) {
cake.transfer(_to, cakeBal);
cake.transfer(_to, _amount);
}
}
function safeCakeTransfer(address _to, uint256 _amount) public onlyOwner {
uint256 cakeBal = cake.balanceOf(address(this));
if (_amount > cakeBal) {
cake.transfer(_to, cakeBal);
cake.transfer(_to, _amount);
}
}
} else {
mapping (address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
mapping (address => uint32) public numCheckpoints;
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping (address => uint) public nonces;
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CAKE::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CAKE::delegateBySig: invalid nonce");
require(now <= expiry, "CAKE::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
} else if (cp.fromBlock < blockNumber) {
} else {
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CAKE::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CAKE::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
} else {
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
return chainId;
}
assembly { chainId := chainid() }
}
| 11,062,214 | [
1,
44,
265,
402,
5190,
598,
611,
1643,
82,
1359,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
670,
265,
402,
5190,
353,
9722,
52,
3462,
2668,
44,
265,
402,
14231,
3155,
2187,
296,
44,
673,
2602,
38,
4307,
6134,
288,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
389,
8501,
15608,
815,
12,
2867,
12,
20,
3631,
389,
3771,
1332,
815,
63,
67,
869,
6487,
389,
8949,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
2867,
389,
2080,
269,
11890,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
70,
321,
24899,
2080,
16,
389,
8949,
1769,
203,
3639,
389,
8501,
15608,
815,
12,
2867,
12,
20,
3631,
389,
3771,
1332,
815,
63,
67,
2080,
6487,
389,
8949,
1769,
203,
565,
289,
203,
203,
203,
203,
565,
3885,
12,
203,
3639,
30830,
14231,
1345,
389,
23780,
203,
565,
30830,
14231,
1345,
1071,
276,
911,
31,
203,
565,
262,
1071,
288,
203,
3639,
276,
911,
273,
389,
23780,
31,
203,
565,
289,
203,
203,
565,
445,
4183,
31089,
5912,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
2254,
5034,
276,
911,
38,
287,
273,
276,
911,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
67,
8949,
405,
276,
911,
38,
287,
13,
288,
203,
5411,
276,
911,
18,
13866,
24899,
869,
16,
276,
911,
38,
287,
1769,
203,
5411,
276,
911,
18,
13866,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
2
] |
./full_match/9001/0xa5194E73D542ca15517f7805b879f7bFD9ec1B27/sources/contracts/BatchStreamer.sol | File contracts/libraries/TransferHelper.sol @notice Library to help safely transfer tokens and handle ETH wrapping and unwrapping of WETH | library TransferHelper {
using SafeERC20 for IERC20;
function transferTokens(
address token,
address from,
address to,
uint256 amount
) internal {
uint256 priorBalance = IERC20(token).balanceOf(address(to));
require(IERC20(token).balanceOf(msg.sender) >= amount, 'THL01');
SafeERC20.safeTransferFrom(IERC20(token), from, to, amount);
uint256 postBalance = IERC20(token).balanceOf(address(to));
require(postBalance - priorBalance == amount, 'THL02');
}
function withdrawTokens(
address token,
address to,
uint256 amount
) internal {
uint256 priorBalance = IERC20(token).balanceOf(address(to));
SafeERC20.safeTransfer(IERC20(token), to, amount);
uint256 postBalance = IERC20(token).balanceOf(address(to));
require(postBalance - priorBalance == amount, 'THL02');
}
}
| 11,534,279 | [
1,
812,
20092,
19,
31417,
19,
5912,
2276,
18,
18281,
225,
18694,
358,
2809,
15303,
7412,
2430,
471,
1640,
512,
2455,
14702,
471,
11014,
1382,
434,
678,
1584,
44,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
12279,
2276,
288,
203,
225,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
225,
445,
7412,
5157,
12,
203,
565,
1758,
1147,
16,
203,
565,
1758,
628,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
3844,
203,
225,
262,
2713,
288,
203,
565,
2254,
5034,
6432,
13937,
273,
467,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
2867,
12,
869,
10019,
203,
565,
2583,
12,
45,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
3576,
18,
15330,
13,
1545,
3844,
16,
296,
2455,
48,
1611,
8284,
203,
565,
14060,
654,
39,
3462,
18,
4626,
5912,
1265,
12,
45,
654,
39,
3462,
12,
2316,
3631,
628,
16,
358,
16,
3844,
1769,
203,
565,
2254,
5034,
1603,
13937,
273,
467,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
2867,
12,
869,
10019,
203,
565,
2583,
12,
2767,
13937,
300,
6432,
13937,
422,
3844,
16,
296,
2455,
48,
3103,
8284,
203,
225,
289,
203,
203,
225,
445,
598,
9446,
5157,
12,
203,
565,
1758,
1147,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
3844,
203,
225,
262,
2713,
288,
203,
565,
2254,
5034,
6432,
13937,
273,
467,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
2867,
12,
869,
10019,
203,
565,
14060,
654,
39,
3462,
18,
4626,
5912,
12,
45,
654,
39,
3462,
12,
2316,
3631,
358,
16,
3844,
1769,
203,
565,
2254,
5034,
1603,
13937,
273,
467,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
2867,
12,
869,
10019,
203,
565,
2
] |
./full_match/80001/0xcA905F6466C253f8195b9940C819Ba32d273447d/sources/contracts/SettingsInternal.sol | * Get NFT Common Commission Rate*/ | function getCommonRate() internal view virtual returns (uint256) {
return getSettings().common_commission_rate;
}
| 860,364 | [
1,
967,
423,
4464,
5658,
1286,
3951,
13025,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
30863,
4727,
1435,
2713,
1476,
5024,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
18283,
7675,
6054,
67,
832,
3951,
67,
5141,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-12
*/
// File: contracts\gsn\Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts\access\Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\libs\SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// 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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @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) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: contracts\token\erc20\IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts\token\erc20\ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
string private _name;
string private _symbol;
uint8 private _decimals;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount));
}
}
// File: contracts\libs\RealMath.sol
pragma solidity ^0.5.0;
/**
* Reference: https://github.com/balancer-labs/balancer-core/blob/master/contracts/BNum.sol
*/
library RealMath {
uint256 private constant BONE = 10 ** 18;
uint256 private constant MIN_BPOW_BASE = 1 wei;
uint256 private constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint256 private constant BPOW_PRECISION = BONE / 10 ** 10;
/**
* @dev
*/
function rtoi(uint256 a)
internal
pure
returns (uint256)
{
return a / BONE;
}
/**
* @dev
*/
function rfloor(uint256 a)
internal
pure
returns (uint256)
{
return rtoi(a) * BONE;
}
/**
* @dev
*/
function radd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
/**
* @dev
*/
function rsub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
(uint256 c, bool flag) = rsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
/**
* @dev
*/
function rsubSign(uint256 a, uint256 b)
internal
pure
returns (uint256, bool)
{
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
/**
* @dev
*/
function rmul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint256 c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
return c1 / BONE;
}
/**
* @dev
*/
function rdiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b != 0, "ERR_DIV_ZERO");
uint256 c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL");
uint256 c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL");
return c1 / b;
}
/**
* @dev
*/
function rpowi(uint256 a, uint256 n)
internal
pure
returns (uint256)
{
uint256 z = n % 2 != 0 ? a : BONE;
for (n /= 2; n != 0; n /= 2) {
a = rmul(a, a);
if (n % 2 != 0) {
z = rmul(z, a);
}
}
return z;
}
/**
* @dev Computes b^(e.w) by splitting it into (b^e)*(b^0.w).
* Use `rpowi` for `b^e` and `rpowK` for k iterations of approximation of b^0.w
*/
function rpow(uint256 base, uint256 exp)
internal
pure
returns (uint256)
{
require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW");
require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH");
uint256 whole = rfloor(exp);
uint256 remain = rsub(exp, whole);
uint256 wholePow = rpowi(base, rtoi(whole));
if (remain == 0) {
return wholePow;
}
uint256 partialResult = rpowApprox(base, remain, BPOW_PRECISION);
return rmul(wholePow, partialResult);
}
/**
* @dev
*/
function rpowApprox(uint256 base, uint256 exp, uint256 precision)
internal
pure
returns (uint256)
{
(uint256 x, bool xneg) = rsubSign(base, BONE);
uint256 a = exp;
uint256 term = BONE;
uint256 sum = term;
bool negative = false;
// term(k) = numer / denom
// = (product(a - i - 1, i = 1--> k) * x ^ k) / (k!)
// Each iteration, multiply previous term by (a - (k - 1)) * x / k
// continue until term is less than precision
for (uint256 i = 1; term >= precision; i++) {
uint256 bigK = i * BONE;
(uint256 c, bool cneg) = rsubSign(a, rsub(bigK, BONE));
term = rmul(term, rmul(c, x));
term = rdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = rsub(sum, term);
} else {
sum = radd(sum, term);
}
}
return sum;
}
}
// File: contracts\libs\Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
// File: contracts\pak\ICollection.sol
pragma solidity ^0.5.0;
interface ICollection {
// ERC721
function transferFrom(address from, address to, uint256 tokenId) external;
// ERC1155
function safeTransferFrom(address from, address to, uint256 tokenId, uint256 amount, bytes calldata data) external;
}
// File: contracts\pak\ASH.sol
pragma solidity ^0.5.0;
contract ASH is Ownable, ERC20 {
using RealMath for uint256;
using Address for address;
bytes4 private constant _ERC1155_RECEIVED = 0xf23a6e61;
event CollectionWhitelist(address collection, bool status);
event AssetWhitelist(address collection, uint256 assetId, bool status);
event CollectionBlacklist(address collection, bool status);
event AssetBlacklist(address collection, uint256 assetId, bool status);
event Swapped(address collection, uint256 assetId, address account, uint256 amount, bool isWhitelist, bool isERC721);
// Mapping "collection" whitelist
mapping(address => bool) private _collectionWhitelist;
// Mapping "asset" whitelist
mapping(address => mapping(uint256 => bool)) private _assetWhitelist;
// Mapping "collection" blacklist
mapping(address => bool) private _collectionBlacklist;
// Mapping "asset" blacklist
mapping(address => mapping(uint256 => bool)) private _assetBlacklist;
bool public isStarted = false;
bool public isERC721Paused = false;
bool public isERC1155Paused = true;
/**
* @dev Throws if NFT swapping does not start yet
*/
modifier started() {
require(isStarted, "ASH: NFT swapping does not start yet");
_;
}
/**
* @dev Throws if collection or asset is in blacklist
*/
modifier notInBlacklist(address collection, uint256 assetId) {
require(!_collectionBlacklist[collection] && !_assetBlacklist[collection][assetId], "ASH: collection or asset is in blacklist");
_;
}
/**
* @dev Initializes the contract settings
*/
constructor(string memory name, string memory symbol)
public
ERC20(name, symbol, 18)
{}
/**
* @dev Starts to allow NFT swapping
*/
function start()
public
onlyOwner
{
isStarted = true;
}
/**
* @dev Pauses NFT (everything) swapping
*/
function pause(bool erc721)
public
onlyOwner
{
if (erc721) {
isERC721Paused = true;
} else {
isERC1155Paused = true;
}
}
/**
* @dev Resumes NFT (everything) swapping
*/
function resume(bool erc721)
public
onlyOwner
{
if (erc721) {
isERC721Paused = false;
} else {
isERC1155Paused = false;
}
}
/**
* @dev Adds or removes collections in whitelist
*/
function updateWhitelist(address[] memory collections, bool status)
public
onlyOwner
{
uint256 length = collections.length;
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
if (_collectionWhitelist[collection] != status) {
_collectionWhitelist[collection] = status;
emit CollectionWhitelist(collection, status);
}
}
}
/**
* @dev Adds or removes assets in whitelist
*/
function updateWhitelist(address[] memory collections, uint256[] memory assetIds, bool status)
public
onlyOwner
{
uint256 length = collections.length;
require(length == assetIds.length, "ASH: length of arrays is not equal");
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
uint256 assetId = assetIds[i];
if (_assetWhitelist[collection][assetId] != status) {
_assetWhitelist[collection][assetId] = status;
emit AssetWhitelist(collection, assetId, status);
}
}
}
/**
* @dev Returns true if collection is in whitelist
*/
function isWhitelist(address collection)
public
view
returns (bool)
{
return _collectionWhitelist[collection];
}
/**
* @dev Returns true if asset is in whitelist
*/
function isWhitelist(address collection, uint256 assetId)
public
view
returns (bool)
{
return _assetWhitelist[collection][assetId];
}
/**
* @dev Adds or removes collections in blacklist
*/
function updateBlacklist(address[] memory collections, bool status)
public
onlyOwner
{
uint256 length = collections.length;
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
if (_collectionBlacklist[collection] != status) {
_collectionBlacklist[collection] = status;
emit CollectionBlacklist(collection, status);
}
}
}
/**
* @dev Adds or removes assets in blacklist
*/
function updateBlacklist(address[] memory collections, uint256[] memory assetIds, bool status)
public
onlyOwner
{
uint256 length = collections.length;
require(length == assetIds.length, "ASH: length of arrays is not equal");
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
uint256 assetId = assetIds[i];
if (_assetBlacklist[collection][assetId] != status) {
_assetBlacklist[collection][assetId] = status;
emit AssetBlacklist(collection, assetId, status);
}
}
}
/**
* @dev Returns true if collection is in blacklist
*/
function isBlacklist(address collection)
public
view
returns (bool)
{
return _collectionBlacklist[collection];
}
/**
* @dev Returns true if asset is in blacklist
*/
function isBlacklist(address collection, uint256 assetId)
public
view
returns (bool)
{
return _assetBlacklist[collection][assetId];
}
/**
* @dev Burns tokens with a specific `amount`
*/
function burn(uint256 amount)
public
{
_burn(_msgSender(), amount);
}
/**
* @dev Calculates token amount that user will receive when burn
*/
function calculateToken(address collection, uint256 assetId)
public
view
returns (bool, uint256)
{
bool whitelist = false;
// Checks if collection or asset in whitelist
if (_collectionWhitelist[collection] || _assetWhitelist[collection][assetId]) {
whitelist = true;
}
uint256 exp = totalSupply().rdiv(1000000 * (10 ** 18));
uint256 multiplier = RealMath.rdiv(1, 2).rpow(exp);
uint256 result;
// Calculates token amount that will issue
if (whitelist) {
result = multiplier.rmul(1000 * (10 ** 18));
} else {
result = multiplier.rmul(multiplier).rmul(2 * (10 ** 18));
}
return (whitelist, result);
}
/**
* @dev Issues ERC20 tokens
*/
function _issueToken(address collection, uint256 assetId, address account, bool isERC721)
private
{
(bool whitelist, uint256 amount) = calculateToken(collection, assetId);
if (!whitelist) {
if (isERC721) {
require(!isERC721Paused, "ASH: ERC721 swapping paused");
} else {
require(!isERC1155Paused, "ASH: ERC1155 swapping paused");
}
}
require(amount > 0, "ASH: amount is invalid");
// Issues tokens
_mint(account, amount);
emit Swapped(collection, assetId, account, amount, whitelist, isERC721);
}
/**
* @dev Swaps ERC721 to ERC20
*/
function swapERC721(address collection, uint256 assetId)
public
started()
notInBlacklist(collection, assetId)
{
address msgSender = _msgSender();
require(!msgSender.isContract(), "ASH: caller is invalid");
// Transfers ERC721 and lock in this smart contract
ICollection(collection).transferFrom(msgSender, address(this), assetId);
// Issues ERC20 tokens for caller
_issueToken(collection, assetId, msgSender, true);
}
/**
* @dev Swaps ERC1155 to ERC20
*/
function swapERC1155(address collection, uint256 assetId)
public
started()
notInBlacklist(collection, assetId)
{
address msgSender = _msgSender();
require(!msgSender.isContract(), "ASH: caller is invalid");
// Transfers ERC1155 and lock in this smart contract
ICollection(collection).safeTransferFrom(msgSender, address(this), assetId, 1, "");
// Issues ERC20 tokens for caller
_issueToken(collection, assetId, msgSender, false);
}
function onERC1155Received(address operator, address from, uint256 id, uint256 value, bytes calldata data)
external
returns (bytes4)
{
return _ERC1155_RECEIVED;
}
} | Mapping "collection" whitelist Mapping "asset" whitelist Mapping "collection" blacklist Mapping "asset" blacklist | contract ASH is Ownable, ERC20 {
using RealMath for uint256;
using Address for address;
bytes4 private constant _ERC1155_RECEIVED = 0xf23a6e61;
event CollectionWhitelist(address collection, bool status);
event AssetWhitelist(address collection, uint256 assetId, bool status);
event CollectionBlacklist(address collection, bool status);
event AssetBlacklist(address collection, uint256 assetId, bool status);
event Swapped(address collection, uint256 assetId, address account, uint256 amount, bool isWhitelist, bool isERC721);
mapping(address => bool) private _collectionWhitelist;
mapping(address => mapping(uint256 => bool)) private _assetWhitelist;
mapping(address => bool) private _collectionBlacklist;
mapping(address => mapping(uint256 => bool)) private _assetBlacklist;
bool public isStarted = false;
bool public isERC721Paused = false;
bool public isERC1155Paused = true;
modifier started() {
require(isStarted, "ASH: NFT swapping does not start yet");
_;
}
modifier notInBlacklist(address collection, uint256 assetId) {
require(!_collectionBlacklist[collection] && !_assetBlacklist[collection][assetId], "ASH: collection or asset is in blacklist");
_;
}
public
ERC20(name, symbol, 18)
constructor(string memory name, string memory symbol)
{}
function start()
public
onlyOwner
{
isStarted = true;
}
function pause(bool erc721)
public
onlyOwner
{
if (erc721) {
isERC721Paused = true;
isERC1155Paused = true;
}
}
function pause(bool erc721)
public
onlyOwner
{
if (erc721) {
isERC721Paused = true;
isERC1155Paused = true;
}
}
} else {
function resume(bool erc721)
public
onlyOwner
{
if (erc721) {
isERC721Paused = false;
isERC1155Paused = false;
}
}
function resume(bool erc721)
public
onlyOwner
{
if (erc721) {
isERC721Paused = false;
isERC1155Paused = false;
}
}
} else {
function updateWhitelist(address[] memory collections, bool status)
public
onlyOwner
{
uint256 length = collections.length;
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
if (_collectionWhitelist[collection] != status) {
_collectionWhitelist[collection] = status;
emit CollectionWhitelist(collection, status);
}
}
}
function updateWhitelist(address[] memory collections, bool status)
public
onlyOwner
{
uint256 length = collections.length;
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
if (_collectionWhitelist[collection] != status) {
_collectionWhitelist[collection] = status;
emit CollectionWhitelist(collection, status);
}
}
}
function updateWhitelist(address[] memory collections, bool status)
public
onlyOwner
{
uint256 length = collections.length;
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
if (_collectionWhitelist[collection] != status) {
_collectionWhitelist[collection] = status;
emit CollectionWhitelist(collection, status);
}
}
}
function updateWhitelist(address[] memory collections, uint256[] memory assetIds, bool status)
public
onlyOwner
{
uint256 length = collections.length;
require(length == assetIds.length, "ASH: length of arrays is not equal");
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
uint256 assetId = assetIds[i];
if (_assetWhitelist[collection][assetId] != status) {
_assetWhitelist[collection][assetId] = status;
emit AssetWhitelist(collection, assetId, status);
}
}
}
function updateWhitelist(address[] memory collections, uint256[] memory assetIds, bool status)
public
onlyOwner
{
uint256 length = collections.length;
require(length == assetIds.length, "ASH: length of arrays is not equal");
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
uint256 assetId = assetIds[i];
if (_assetWhitelist[collection][assetId] != status) {
_assetWhitelist[collection][assetId] = status;
emit AssetWhitelist(collection, assetId, status);
}
}
}
function updateWhitelist(address[] memory collections, uint256[] memory assetIds, bool status)
public
onlyOwner
{
uint256 length = collections.length;
require(length == assetIds.length, "ASH: length of arrays is not equal");
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
uint256 assetId = assetIds[i];
if (_assetWhitelist[collection][assetId] != status) {
_assetWhitelist[collection][assetId] = status;
emit AssetWhitelist(collection, assetId, status);
}
}
}
function isWhitelist(address collection)
public
view
returns (bool)
{
return _collectionWhitelist[collection];
}
function isWhitelist(address collection, uint256 assetId)
public
view
returns (bool)
{
return _assetWhitelist[collection][assetId];
}
function updateBlacklist(address[] memory collections, bool status)
public
onlyOwner
{
uint256 length = collections.length;
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
if (_collectionBlacklist[collection] != status) {
_collectionBlacklist[collection] = status;
emit CollectionBlacklist(collection, status);
}
}
}
function updateBlacklist(address[] memory collections, bool status)
public
onlyOwner
{
uint256 length = collections.length;
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
if (_collectionBlacklist[collection] != status) {
_collectionBlacklist[collection] = status;
emit CollectionBlacklist(collection, status);
}
}
}
function updateBlacklist(address[] memory collections, bool status)
public
onlyOwner
{
uint256 length = collections.length;
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
if (_collectionBlacklist[collection] != status) {
_collectionBlacklist[collection] = status;
emit CollectionBlacklist(collection, status);
}
}
}
function updateBlacklist(address[] memory collections, uint256[] memory assetIds, bool status)
public
onlyOwner
{
uint256 length = collections.length;
require(length == assetIds.length, "ASH: length of arrays is not equal");
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
uint256 assetId = assetIds[i];
if (_assetBlacklist[collection][assetId] != status) {
_assetBlacklist[collection][assetId] = status;
emit AssetBlacklist(collection, assetId, status);
}
}
}
function updateBlacklist(address[] memory collections, uint256[] memory assetIds, bool status)
public
onlyOwner
{
uint256 length = collections.length;
require(length == assetIds.length, "ASH: length of arrays is not equal");
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
uint256 assetId = assetIds[i];
if (_assetBlacklist[collection][assetId] != status) {
_assetBlacklist[collection][assetId] = status;
emit AssetBlacklist(collection, assetId, status);
}
}
}
function updateBlacklist(address[] memory collections, uint256[] memory assetIds, bool status)
public
onlyOwner
{
uint256 length = collections.length;
require(length == assetIds.length, "ASH: length of arrays is not equal");
for (uint256 i = 0; i < length; i++) {
address collection = collections[i];
uint256 assetId = assetIds[i];
if (_assetBlacklist[collection][assetId] != status) {
_assetBlacklist[collection][assetId] = status;
emit AssetBlacklist(collection, assetId, status);
}
}
}
function isBlacklist(address collection)
public
view
returns (bool)
{
return _collectionBlacklist[collection];
}
function isBlacklist(address collection, uint256 assetId)
public
view
returns (bool)
{
return _assetBlacklist[collection][assetId];
}
function burn(uint256 amount)
public
{
_burn(_msgSender(), amount);
}
function calculateToken(address collection, uint256 assetId)
public
view
returns (bool, uint256)
{
bool whitelist = false;
if (_collectionWhitelist[collection] || _assetWhitelist[collection][assetId]) {
whitelist = true;
}
uint256 exp = totalSupply().rdiv(1000000 * (10 ** 18));
uint256 multiplier = RealMath.rdiv(1, 2).rpow(exp);
uint256 result;
if (whitelist) {
result = multiplier.rmul(1000 * (10 ** 18));
result = multiplier.rmul(multiplier).rmul(2 * (10 ** 18));
}
return (whitelist, result);
}
function calculateToken(address collection, uint256 assetId)
public
view
returns (bool, uint256)
{
bool whitelist = false;
if (_collectionWhitelist[collection] || _assetWhitelist[collection][assetId]) {
whitelist = true;
}
uint256 exp = totalSupply().rdiv(1000000 * (10 ** 18));
uint256 multiplier = RealMath.rdiv(1, 2).rpow(exp);
uint256 result;
if (whitelist) {
result = multiplier.rmul(1000 * (10 ** 18));
result = multiplier.rmul(multiplier).rmul(2 * (10 ** 18));
}
return (whitelist, result);
}
function calculateToken(address collection, uint256 assetId)
public
view
returns (bool, uint256)
{
bool whitelist = false;
if (_collectionWhitelist[collection] || _assetWhitelist[collection][assetId]) {
whitelist = true;
}
uint256 exp = totalSupply().rdiv(1000000 * (10 ** 18));
uint256 multiplier = RealMath.rdiv(1, 2).rpow(exp);
uint256 result;
if (whitelist) {
result = multiplier.rmul(1000 * (10 ** 18));
result = multiplier.rmul(multiplier).rmul(2 * (10 ** 18));
}
return (whitelist, result);
}
} else {
function _issueToken(address collection, uint256 assetId, address account, bool isERC721)
private
{
(bool whitelist, uint256 amount) = calculateToken(collection, assetId);
if (!whitelist) {
if (isERC721) {
require(!isERC721Paused, "ASH: ERC721 swapping paused");
require(!isERC1155Paused, "ASH: ERC1155 swapping paused");
}
}
require(amount > 0, "ASH: amount is invalid");
emit Swapped(collection, assetId, account, amount, whitelist, isERC721);
}
function _issueToken(address collection, uint256 assetId, address account, bool isERC721)
private
{
(bool whitelist, uint256 amount) = calculateToken(collection, assetId);
if (!whitelist) {
if (isERC721) {
require(!isERC721Paused, "ASH: ERC721 swapping paused");
require(!isERC1155Paused, "ASH: ERC1155 swapping paused");
}
}
require(amount > 0, "ASH: amount is invalid");
emit Swapped(collection, assetId, account, amount, whitelist, isERC721);
}
function _issueToken(address collection, uint256 assetId, address account, bool isERC721)
private
{
(bool whitelist, uint256 amount) = calculateToken(collection, assetId);
if (!whitelist) {
if (isERC721) {
require(!isERC721Paused, "ASH: ERC721 swapping paused");
require(!isERC1155Paused, "ASH: ERC1155 swapping paused");
}
}
require(amount > 0, "ASH: amount is invalid");
emit Swapped(collection, assetId, account, amount, whitelist, isERC721);
}
} else {
_mint(account, amount);
function swapERC721(address collection, uint256 assetId)
public
started()
notInBlacklist(collection, assetId)
{
address msgSender = _msgSender();
require(!msgSender.isContract(), "ASH: caller is invalid");
ICollection(collection).transferFrom(msgSender, address(this), assetId);
_issueToken(collection, assetId, msgSender, true);
}
function swapERC1155(address collection, uint256 assetId)
public
started()
notInBlacklist(collection, assetId)
{
address msgSender = _msgSender();
require(!msgSender.isContract(), "ASH: caller is invalid");
ICollection(collection).safeTransferFrom(msgSender, address(this), assetId, 1, "");
_issueToken(collection, assetId, msgSender, false);
}
function onERC1155Received(address operator, address from, uint256 id, uint256 value, bytes calldata data)
external
returns (bytes4)
{
return _ERC1155_RECEIVED;
}
} | 15,284,294 | [
1,
3233,
315,
5548,
6,
10734,
9408,
315,
9406,
6,
10734,
9408,
315,
5548,
6,
11709,
9408,
315,
9406,
6,
11709,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
432,
2664,
353,
14223,
6914,
16,
4232,
39,
3462,
288,
203,
203,
565,
1450,
15987,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
1731,
24,
3238,
5381,
389,
654,
39,
2499,
2539,
67,
27086,
20764,
273,
374,
5841,
4366,
69,
26,
73,
9498,
31,
203,
203,
565,
871,
2200,
18927,
12,
2867,
1849,
16,
1426,
1267,
1769,
203,
565,
871,
10494,
18927,
12,
2867,
1849,
16,
2254,
5034,
3310,
548,
16,
1426,
1267,
1769,
203,
203,
565,
871,
2200,
25811,
12,
2867,
1849,
16,
1426,
1267,
1769,
203,
565,
871,
10494,
25811,
12,
2867,
1849,
16,
2254,
5034,
3310,
548,
16,
1426,
1267,
1769,
203,
203,
565,
871,
12738,
1845,
12,
2867,
1849,
16,
2254,
5034,
3310,
548,
16,
1758,
2236,
16,
2254,
5034,
3844,
16,
1426,
353,
18927,
16,
1426,
353,
654,
39,
27,
5340,
1769,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
5548,
18927,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
1426,
3719,
3238,
389,
9406,
18927,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
5548,
25811,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
1426,
3719,
3238,
389,
9406,
25811,
31,
203,
203,
565,
1426,
1071,
28481,
273,
629,
31,
203,
203,
565,
1426,
1071,
353,
654,
39,
27,
5340,
28590,
273,
629,
31,
203,
565,
1426,
1071,
353,
654,
39,
2499,
2539,
28590,
273,
638,
31,
203,
203,
203,
565,
9606,
5746,
1435,
2
] |
./full_match/1/0x1A1691e97FB05b3A2B8841f98e0486113De823A1/sources/AaveImportTakerV2.sol | solhint-disable-next-line func-name-mixedcase | function Log(address _contract, address _caller, string memory _logName, bytes memory _data)
public
{
emit LogEvent(_contract, _caller, _logName, _data);
}
| 4,994,729 | [
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
1326,
17,
529,
17,
19562,
3593,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1827,
12,
2867,
389,
16351,
16,
1758,
389,
16140,
16,
533,
3778,
389,
1330,
461,
16,
1731,
3778,
389,
892,
13,
203,
3639,
1071,
203,
565,
288,
203,
3639,
3626,
1827,
1133,
24899,
16351,
16,
389,
16140,
16,
389,
1330,
461,
16,
389,
892,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.