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 |
---|---|---|---|---|---|---|
./partial_match/3/0x86DAB835f4A9B948C6fF49BF8bb7653e6A183202/sources/COLOR.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 {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
}
constructor () internal {
_paused = false;
}
function paused() public view returns (bool) {
return _paused;
}
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
| 16,612,558 | [
1,
8924,
1605,
1492,
5360,
2325,
358,
2348,
392,
801,
24530,
2132,
12860,
716,
848,
506,
10861,
635,
392,
10799,
2236,
18,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
10429,
1375,
13723,
1248,
28590,
68,
471,
1375,
13723,
28590,
9191,
1492,
848,
506,
6754,
358,
326,
4186,
434,
3433,
6835,
18,
3609,
716,
2898,
903,
486,
506,
6790,
16665,
635,
8616,
6508,
333,
1605,
16,
1338,
3647,
326,
10429,
854,
1378,
316,
3166,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
17801,
6835,
21800,
16665,
353,
1772,
288,
203,
565,
871,
21800,
3668,
12,
2867,
2236,
1769,
203,
203,
565,
871,
1351,
8774,
3668,
12,
2867,
2236,
1769,
203,
203,
565,
1426,
3238,
389,
8774,
3668,
31,
203,
203,
97,
203,
203,
203,
565,
3885,
1832,
2713,
288,
203,
3639,
389,
8774,
3668,
273,
629,
31,
203,
565,
289,
203,
203,
565,
445,
17781,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
8774,
3668,
31,
203,
565,
289,
203,
203,
565,
9606,
1347,
1248,
28590,
1435,
288,
203,
3639,
2583,
12,
5,
67,
8774,
3668,
16,
315,
16507,
16665,
30,
17781,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1347,
28590,
1435,
288,
203,
3639,
2583,
24899,
8774,
3668,
16,
315,
16507,
16665,
30,
486,
17781,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
389,
19476,
1435,
2713,
5024,
1347,
1248,
28590,
288,
203,
3639,
389,
8774,
3668,
273,
638,
31,
203,
3639,
3626,
21800,
3668,
24899,
3576,
12021,
10663,
203,
565,
289,
203,
203,
565,
445,
389,
318,
19476,
1435,
2713,
5024,
1347,
28590,
288,
203,
3639,
389,
8774,
3668,
273,
629,
31,
203,
3639,
3626,
1351,
8774,
3668,
24899,
3576,
12021,
10663,
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
] |
/**
*Submitted for verification at Etherscan.io on 2020-09-24
*/
// File: contracts/token/DMCGovernanceStorage.sol
pragma solidity 0.5.17;
contract DMCGovernanceStorage {
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
}
// File: contracts/lib/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.17;
/**
* @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: contracts/token/DMCTokenStorage.sol
pragma solidity 0.5.17;
// Storage for a DMC token
contract DMCTokenStorage {
using SafeMath for uint256;
/**
* @dev Guard variable for re-entrancy checks. Not currently used
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Governor for this contract
*/
address public gov;
/**
* @notice Pending governance for this contract
*/
address public pendingGov;
/**
* @notice Total supply of DMCs
*/
uint256 public totalSupply;
mapping (address => uint256) internal _DMCBalances;
mapping (address => mapping (address => uint256)) internal _allowedFragments;
}
// File: contracts/token/DMCTokenInterface.sol
pragma solidity 0.5.17;
contract DMCTokenInterface is DMCTokenStorage, DMCGovernanceStorage {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/*** Gov Events ***/
/**
* @notice Event emitted when pendingGov is changed
*/
event NewPendingGov(address oldPendingGov, address newPendingGov);
/**
* @notice Event emitted when gov is changed
*/
event NewGov(address oldGov, address newGov);
/* - ERC20 Events - */
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Tokens minted event
*/
event Mint(address to, uint256 amount);
// Public functions
function transfer(address to, uint256 value) external returns(bool);
function transferFrom(address from, address to, uint256 value) external returns(bool);
function balanceOf(address who) external view returns(uint256);
function allowance(address owner_, address spender) external view returns(uint256);
function approve(address spender, uint256 value) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
/* - Governance Functions - */
function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
function delegate(address delegatee) external;
function delegates(address delegator) external view returns (address);
function getCurrentVotes(address account) external view returns (uint256);
/* - Permissioned/Governance functions - */
function _setPendingGov(address pendingGov_) external;
function _acceptGov() external;
}
// File: contracts/token/DMCGovernance.sol
pragma solidity 0.5.17;
contract DMCGovernanceToken is DMCTokenInterface {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
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), "DMC::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "DMC::delegateBySig: invalid nonce");
require(now <= expiry, "DMC::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "DMC::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = _DMCBalances[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)) {
// decrease old representative
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)) {
// increase new representative
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, "DMC::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
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;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/token/DMC.sol
pragma solidity 0.5.17;
contract DMCToken is DMCGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyGov
returns (bool)
{
require(totalSupply + amount <= 88_000_000 * 1e18, 'max supply reached');
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// add balance
_DMCBalances[to] = _DMCBalances[to].add(amount);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], amount);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// sub from balance of sender
_DMCBalances[msg.sender] = _DMCBalances[msg.sender].sub(value); //injected INTEGER OVERFLOW OR UNDERFLOW
// add to balance of receiver
_DMCBalances[to] = _DMCBalances[to].add(value); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); //injected INTEGER OVERFLOW OR UNDERFLOW
// sub from from
_DMCBalances[from] = _DMCBalances[from].sub(value); //injected INTEGER OVERFLOW OR UNDERFLOW
_DMCBalances[to] = _DMCBalances[to].add(value); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], value);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _DMCBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @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)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); //injected INTEGER OVERFLOW OR UNDERFLOW
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
}
contract DMC is DMCToken {
/**
* @notice Initialize the new money market
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_,
address initial_owner,
uint256 initSupply_
)
public
{
require(initSupply_ > 0, "0 init supply");
super.initialize(name_, symbol_, decimals_);
totalSupply = initSupply_;
_DMCBalances[initial_owner] = initSupply_;
// owner renounces ownership after deployment as they need to set
// rebaser and incentivizer
// gov = gov_;
}
}
// File: contracts/token/DMCDelegate.sol
pragma solidity 0.5.17;
contract DMCDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract DMCDelegatorInterface is DMCDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract DMCDelegateInterface is DMCDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
contract DMCDelegate is DMC, DMCDelegateInterface {
/**
* @notice Construct an empty delegate
*/
constructor() public {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == gov, "only the gov may call _becomeImplementation");
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == gov, "only the gov may call _resignImplementation");
}
} | * @dev Transfer tokens from one address to another. @param from The address you want to send tokens from. @param to The address you want to transfer to. @param value The amount of tokens to be transferred./ decrease allowance sub from from | function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], value);
return true;
}
| 15,869,558 | [
1,
5912,
2430,
628,
1245,
1758,
358,
4042,
18,
225,
628,
1021,
1758,
1846,
2545,
358,
1366,
2430,
628,
18,
225,
358,
1021,
1758,
1846,
2545,
358,
7412,
358,
18,
225,
460,
1021,
3844,
434,
2430,
358,
506,
906,
4193,
18,
19,
20467,
1699,
1359,
720,
628,
628,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
460,
13,
203,
3639,
3903,
203,
3639,
923,
18241,
12,
869,
13,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
203,
203,
203,
203,
3639,
3626,
12279,
12,
2080,
16,
358,
16,
460,
1769,
203,
203,
3639,
389,
8501,
15608,
815,
24899,
3771,
1332,
815,
63,
2080,
6487,
389,
3771,
1332,
815,
63,
869,
6487,
460,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xda9846665Bdb44b0d0CAFFd0d1D4A539932BeBdf/sources/VeBoostDelegationMultiRewards.sol | @notice Set the minimum duration for delegate boost @param _duration minimum boosting duration | function setMinBoostDuration(uint256 _duration) external onlyOwner {
minBoostDuration = _duration;
emit MinBoostDurationSet(_duration);
}
| 2,635,833 | [
1,
694,
326,
5224,
3734,
364,
7152,
14994,
225,
389,
8760,
5224,
14994,
310,
3734,
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,
27724,
26653,
5326,
12,
11890,
5034,
389,
8760,
13,
3903,
1338,
5541,
288,
203,
3639,
1131,
26653,
5326,
273,
389,
8760,
31,
203,
3639,
3626,
5444,
26653,
5326,
694,
24899,
8760,
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
] |
./full_match/80001/0x809420EEE145CE61be213Bd4AE40885cE8b11E8e/sources/contracts/testnetGenerateV2.sol | * @title TestnetGenerate @dev A contract for NFTs with different minting phases and whitelist verification./ | contract TestnetGenerateV2 is ERC721, Ownable, Pausable {
using LibPRNG for LibPRNG.PRNG;
using LibString for uint256;
uint256 public remainingSupply;
uint256 private updatedRemainingSupply;
uint256 public mintPrice;
string public baseTokenURI;
Phases public currentPhase;
mapping(uint256 => uint256) private _availableTokens;
mapping(Phases => bytes32) public merkleRoot;
mapping(Phases => uint32[2]) internal _phaseConfig;
mapping(Phases => uint256) public phaseMintedAmount;
mapping(address => uint256[]) private ownedTokens;
uint256 constant PHASE_TWO_SUPPLY_WL = 300;
uint256 constant PHASE_TWO_SUPPLY_FCFS = 300;
uint256 constant PHASE_FINAL_SUPPLY_WL = 300;
uint256 constant PHASE_FINAL_SUPPLY_FCFS = 300;
uint256 alphaMintPrice = 0 ether;
uint256 twoWLMintPrice = 0 ether;
uint256 twoFCFSMintPrice = 0 ether;
uint256 twoPublicMintPrice = 0 ether;
uint256 finalWLMintPrice = 0 ether;
uint256 finalFCFSMintPrice = 0 ether;
uint256 finalPublicMintPrice = 0 ether;
pragma solidity ^0.8.18;
import {LibPRNG} from "solady/src/utils/LibPRNG.sol";
import {LibString} from "solady/src/utils/LibString.sol";
enum Phases {
}
constructor() ERC721("Generate NFT", "AWNFT") {
merkleRoot[
Phases.TWOWL
] = 0x3179060ef840c2128dccef21faf392c34a8b187bb9520458771ffd94a941ec97;
merkleRoot[
Phases.FINALWL
] = 0x3179060ef840c2128dccef21faf392c34a8b187bb9520458771ffd94a941ec97;
remainingSupply = MAX_SUPPLY;
}
function setCurrentPhase(uint256 _phase) public onlyOwner {
currentPhase = Phases(_phase);
}
function setMerkleRoot(Phases _phase, bytes32 _root) public onlyOwner {
merkleRoot[_phase] = _root;
}
function mintWL(bytes32[] memory _proof) public payable {
require(
_getWLMintEligibilityAtCurrentPhase(msg.sender, _proof),
"Not eligible to mint"
);
mintPrice = calculateTotalMintPrice();
require(msg.value == mintPrice, "Insufficient funds");
uint256 tokenId = getRandomTokenId();
_safeMint(msg.sender, tokenId);
ownedTokens[msg.sender].push(tokenId);
phaseMintedAmount[currentPhase]++;
remainingSupply--;
}
function mint() public payable onlyOwner {
require(_getMintEligibilityAtCurrentPhase(), "Not eligible to mint");
mintPrice = calculateTotalMintPrice();
require(msg.value == mintPrice, "Insufficient funds");
uint256 tokenId = getRandomTokenId();
_safeMint(msg.sender, tokenId);
ownedTokens[msg.sender].push(tokenId);
phaseMintedAmount[currentPhase]++;
remainingSupply--;
}
function setBaseURI(string calldata baseURI) public onlyOwner {
baseTokenURI = baseURI;
}
function getOwnedTokens(
address walletAddress
) public view returns (uint256[] memory) {
return ownedTokens[walletAddress];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: caller is not token owner or approved"
);
_transfer(from, to, tokenId);
uint256 tokenIndex = findOwnedTokenIndex(from, tokenId);
if (tokenIndex < ownedTokens[from].length) {
ownedTokens[from][tokenIndex] = ownedTokens[from][
ownedTokens[from].length - 1
];
ownedTokens[from].pop();
}
ownedTokens[to].push(tokenId);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: caller is not token owner or approved"
);
_transfer(from, to, tokenId);
uint256 tokenIndex = findOwnedTokenIndex(from, tokenId);
if (tokenIndex < ownedTokens[from].length) {
ownedTokens[from][tokenIndex] = ownedTokens[from][
ownedTokens[from].length - 1
];
ownedTokens[from].pop();
}
ownedTokens[to].push(tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: caller is not token owner or approved"
);
_safeTransfer(from, to, tokenId, data);
uint256 tokenIndex = findOwnedTokenIndex(from, tokenId);
if (tokenIndex < ownedTokens[from].length) {
ownedTokens[from][tokenIndex] = ownedTokens[from][
ownedTokens[from].length - 1
];
ownedTokens[from].pop();
}
ownedTokens[to].push(tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: caller is not token owner or approved"
);
_safeTransfer(from, to, tokenId, data);
uint256 tokenIndex = findOwnedTokenIndex(from, tokenId);
if (tokenIndex < ownedTokens[from].length) {
ownedTokens[from][tokenIndex] = ownedTokens[from][
ownedTokens[from].length - 1
];
ownedTokens[from].pop();
}
ownedTokens[to].push(tokenId);
}
function tokenURI(
uint256 _tokenId
) public view virtual override returns (string memory) {
require(
_exists(_tokenId),
"ERC721 Metadata: URI query for nonexistent token"
);
return
bytes(baseTokenURI).length > 0
? string(
abi.encodePacked(baseTokenURI, _tokenId.toString(), ".json")
)
: "";
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function withdraw() public onlyOwner {
require(success, "Transfer Failed");
}
(bool success, ) = msg.sender.call{value: address(this).balance}("");
function getRandomTokenId() internal returns (uint256) {
require(remainingSupply != 0, "All minted");
LibPRNG.PRNG memory prng = LibPRNG.PRNG(
uint256(
keccak256(abi.encodePacked(block.timestamp, block.prevrandao))
)
);
uint256 randomIndex = prng.uniform(remainingSupply);
uint256 tokenId = getAvailableTokenAtIndex(
randomIndex,
remainingSupply
);
return tokenId;
}
function getAvailableTokenAtIndex(
uint256 indexToUse,
uint256 updatedNumAvailableTokens
) internal returns (uint256 result) {
uint256 valAtIndex = _availableTokens[indexToUse];
uint256 lastIndex = updatedNumAvailableTokens - 1;
uint256 lastValInArray = _availableTokens[lastIndex];
result = valAtIndex == 0 ? indexToUse : valAtIndex;
if (indexToUse != lastIndex) {
_availableTokens[indexToUse] = lastValInArray == 0
? lastIndex
: lastValInArray;
}
if (lastValInArray != 0) {
delete _availableTokens[lastIndex];
}
}
function getAvailableTokenAtIndex(
uint256 indexToUse,
uint256 updatedNumAvailableTokens
) internal returns (uint256 result) {
uint256 valAtIndex = _availableTokens[indexToUse];
uint256 lastIndex = updatedNumAvailableTokens - 1;
uint256 lastValInArray = _availableTokens[lastIndex];
result = valAtIndex == 0 ? indexToUse : valAtIndex;
if (indexToUse != lastIndex) {
_availableTokens[indexToUse] = lastValInArray == 0
? lastIndex
: lastValInArray;
}
if (lastValInArray != 0) {
delete _availableTokens[lastIndex];
}
}
function getAvailableTokenAtIndex(
uint256 indexToUse,
uint256 updatedNumAvailableTokens
) internal returns (uint256 result) {
uint256 valAtIndex = _availableTokens[indexToUse];
uint256 lastIndex = updatedNumAvailableTokens - 1;
uint256 lastValInArray = _availableTokens[lastIndex];
result = valAtIndex == 0 ? indexToUse : valAtIndex;
if (indexToUse != lastIndex) {
_availableTokens[indexToUse] = lastValInArray == 0
? lastIndex
: lastValInArray;
}
if (lastValInArray != 0) {
delete _availableTokens[lastIndex];
}
}
function calculateTotalMintPrice()
internal
view
returns (uint256 totalMintPrice)
{
if (currentPhase == Phases.ALPHA) {
totalMintPrice = alphaMintPrice;
totalMintPrice = twoWLMintPrice;
totalMintPrice = twoFCFSMintPrice;
totalMintPrice = twoPublicMintPrice;
totalMintPrice = finalWLMintPrice;
totalMintPrice = finalFCFSMintPrice;
totalMintPrice = finalPublicMintPrice;
}
}
function calculateTotalMintPrice()
internal
view
returns (uint256 totalMintPrice)
{
if (currentPhase == Phases.ALPHA) {
totalMintPrice = alphaMintPrice;
totalMintPrice = twoWLMintPrice;
totalMintPrice = twoFCFSMintPrice;
totalMintPrice = twoPublicMintPrice;
totalMintPrice = finalWLMintPrice;
totalMintPrice = finalFCFSMintPrice;
totalMintPrice = finalPublicMintPrice;
}
}
} else if (currentPhase == Phases.TWOWL) {
} else if (currentPhase == Phases.TWOFCFS) {
} else if (currentPhase == Phases.TWOPB) {
} else if (currentPhase == Phases.FINALWL) {
} else if (currentPhase == Phases.FINALFCFS) {
} else {
function _isWLPhase(
Phases _phase,
address user_,
bytes32[] memory proof_
) internal view returns (bool) {
if (_phase == Phases.TWOWL) {
return _isTwoWL(user_, proof_);
return _isFinalWL(user_, proof_);
}
revert("WL Phase does not exist");
}
function _isWLPhase(
Phases _phase,
address user_,
bytes32[] memory proof_
) internal view returns (bool) {
if (_phase == Phases.TWOWL) {
return _isTwoWL(user_, proof_);
return _isFinalWL(user_, proof_);
}
revert("WL Phase does not exist");
}
} else if (_phase == Phases.FINALWL) {
function _isPhase(Phases _phase) internal view returns (bool) {
if (_phase == Phases.ALPHA) {
return _isALPHA();
return _isTwoFCFS();
return _isTwoPublic();
return _isFinalFCFS();
return _isFinalPublic();
}
revert("Phase does not exist");
}
function _isPhase(Phases _phase) internal view returns (bool) {
if (_phase == Phases.ALPHA) {
return _isALPHA();
return _isTwoFCFS();
return _isTwoPublic();
return _isFinalFCFS();
return _isFinalPublic();
}
revert("Phase does not exist");
}
} else if (_phase == Phases.TWOFCFS) {
} else if (_phase == Phases.TWOPB) {
} else if (_phase == Phases.FINALFCFS) {
} else if (_phase == Phases.PUBLIC) {
function _isTwoWL(
address user_,
bytes32[] memory proof_
) internal view returns (bool) {
require(
phaseMintedAmount[currentPhase] < PHASE_TWO_SUPPLY_WL,
"Exceeded mint phase amount"
);
return _verify(proof_, user_, merkleRoot[Phases.TWOWL]);
}
function _isFinalWL(
address user_,
bytes32[] memory proof_
) internal view returns (bool) {
require(
phaseMintedAmount[currentPhase] < PHASE_FINAL_SUPPLY_WL,
"Exceeded mint phase amount"
);
return _verify(proof_, user_, merkleRoot[Phases.FINALWL]);
}
function _isALPHA() internal view returns (bool) {
require(
phaseMintedAmount[currentPhase] < PHASE_ALPHA_SUPPLY,
"Exceeded mint phase amount"
);
return true;
}
function _isTwoFCFS() internal view returns (bool) {
require(
phaseMintedAmount[currentPhase] < PHASE_TWO_SUPPLY_FCFS,
"Exceeded mint phase amount"
);
return true;
}
function _isTwoPublic() internal view returns (bool) {
require(
phaseMintedAmount[currentPhase] < PHASE_TWO_SUPPLY,
"Exceeded mint phase amount"
);
return true;
}
function _isFinalFCFS() internal view returns (bool) {
require(
phaseMintedAmount[currentPhase] < PHASE_FINAL_SUPPLY_FCFS,
"Exceeded mint phase amount"
);
return true;
}
function _isFinalPublic() internal view returns (bool) {
require(
phaseMintedAmount[currentPhase] < PHASE_FINAL_SUPPLY,
"Exceeded mint phase amount"
);
return true;
}
function _getWLMintEligibilityAtCurrentPhase(
address _user,
bytes32[] memory _proof
) internal view returns (bool mintEligibility) {
if (currentPhase == Phases.TWOWL) {
mintEligibility = _isWLPhase(Phases.TWOWL, _user, _proof);
mintEligibility = _isWLPhase(Phases.FINALWL, _user, _proof);
mintEligibility = false;
}
return mintEligibility;
}
function _getWLMintEligibilityAtCurrentPhase(
address _user,
bytes32[] memory _proof
) internal view returns (bool mintEligibility) {
if (currentPhase == Phases.TWOWL) {
mintEligibility = _isWLPhase(Phases.TWOWL, _user, _proof);
mintEligibility = _isWLPhase(Phases.FINALWL, _user, _proof);
mintEligibility = false;
}
return mintEligibility;
}
} else if (currentPhase == Phases.FINALWL) {
} else {
function _getMintEligibilityAtCurrentPhase()
internal
view
returns (bool mintEligibility)
{
if (currentPhase == Phases.ALPHA) {
mintEligibility = _isPhase(Phases.ALPHA);
mintEligibility = _isPhase(Phases.TWOFCFS);
mintEligibility = _isPhase(Phases.TWOPB);
mintEligibility = _isPhase(Phases.FINALFCFS);
mintEligibility = _isPhase(Phases.PUBLIC);
mintEligibility = false;
}
return mintEligibility;
}
function _getMintEligibilityAtCurrentPhase()
internal
view
returns (bool mintEligibility)
{
if (currentPhase == Phases.ALPHA) {
mintEligibility = _isPhase(Phases.ALPHA);
mintEligibility = _isPhase(Phases.TWOFCFS);
mintEligibility = _isPhase(Phases.TWOPB);
mintEligibility = _isPhase(Phases.FINALFCFS);
mintEligibility = _isPhase(Phases.PUBLIC);
mintEligibility = false;
}
return mintEligibility;
}
} else if (currentPhase == Phases.TWOFCFS) {
} else if (currentPhase == Phases.TWOPB) {
} else if (currentPhase == Phases.FINALFCFS) {
} else if (currentPhase == Phases.PUBLIC) {
} else {
function _verify(
bytes32[] memory _proof,
address _user,
bytes32 _root
) internal pure returns (bool) {
bytes32 leaf = keccak256(abi.encode(_user));
bool verifyResult = MerkleProof.verify(_proof, _root, leaf);
require(verifyResult, "Invalid proof");
return true;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId,
uint256 batchSize
) internal override whenNotPaused {
super._beforeTokenTransfer(from, to, tokenId, batchSize);
}
function findOwnedTokenIndex(
address owner,
uint256 tokenId
) internal view returns (uint256) {
for (uint256 i = 0; i < ownedTokens[owner].length; i++) {
if (ownedTokens[owner][i] == tokenId) {
return i;
}
}
revert("Token id not found");
}
function findOwnedTokenIndex(
address owner,
uint256 tokenId
) internal view returns (uint256) {
for (uint256 i = 0; i < ownedTokens[owner].length; i++) {
if (ownedTokens[owner][i] == tokenId) {
return i;
}
}
revert("Token id not found");
}
function findOwnedTokenIndex(
address owner,
uint256 tokenId
) internal view returns (uint256) {
for (uint256 i = 0; i < ownedTokens[owner].length; i++) {
if (ownedTokens[owner][i] == tokenId) {
return i;
}
}
revert("Token id not found");
}
}
| 839,989 | [
1,
4709,
2758,
4625,
225,
432,
6835,
364,
423,
4464,
87,
598,
3775,
312,
474,
310,
24642,
471,
10734,
11805,
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
] | [
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,
7766,
2758,
4625,
58,
22,
353,
4232,
39,
27,
5340,
16,
14223,
6914,
16,
21800,
16665,
288,
203,
565,
1450,
10560,
8025,
4960,
364,
10560,
8025,
4960,
18,
8025,
4960,
31,
203,
565,
1450,
10560,
780,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
1071,
4463,
3088,
1283,
31,
203,
565,
2254,
5034,
3238,
3526,
11429,
3088,
1283,
31,
203,
565,
2254,
5034,
1071,
312,
474,
5147,
31,
203,
565,
533,
1071,
1026,
1345,
3098,
31,
203,
565,
4360,
3304,
1071,
783,
11406,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
3238,
389,
5699,
5157,
31,
203,
565,
2874,
12,
3731,
3304,
516,
1731,
1578,
13,
1071,
30235,
2375,
31,
203,
565,
2874,
12,
3731,
3304,
516,
2254,
1578,
63,
22,
5717,
2713,
389,
13961,
809,
31,
203,
565,
2874,
12,
3731,
3304,
516,
2254,
5034,
13,
1071,
6855,
49,
474,
329,
6275,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
63,
5717,
3238,
16199,
5157,
31,
203,
203,
565,
2254,
5034,
5381,
15490,
4429,
67,
18869,
51,
67,
13272,
23893,
67,
59,
48,
273,
11631,
31,
203,
565,
2254,
5034,
5381,
15490,
4429,
67,
18869,
51,
67,
13272,
23893,
67,
4488,
4931,
273,
11631,
31,
203,
565,
2254,
5034,
5381,
15490,
4429,
67,
7263,
1013,
67,
13272,
23893,
67,
59,
48,
273,
11631,
31,
203,
565,
2254,
5034,
5381,
15490,
4429,
67,
7263,
1013,
67,
13272,
23893,
67,
4488,
4931,
273,
11631,
31,
203,
203,
565,
2254,
5034,
4190,
49,
474,
5147,
273,
374,
225,
2437,
2
] |
// SPDX-License-Identifier: UNLICENSED
pragma experimental ABIEncoderV2;
pragma solidity ^0.7.6;
import "../../common/OVLTokenTypes.sol";
import "../libs/SafeMath.sol";
import "../../interfaces/IDeltaToken.sol";
contract TeamShareTimelock {
using SafeMath for uint256;
IDeltaToken immutable public DELTA_TOKEN;
uint256 constant private TOTAL_EXPECTED_AMOUNT = 225_000 ether;
/// @dev first month is paid out at the start
uint256 constant private INITIAL_CLAIM = 18_750 ether;
uint256 constant private VESTING_AMOUNT = TOTAL_EXPECTED_AMOUNT - INITIAL_CLAIM;
/// @dev 11 months since we advance the first month so it starts
/// vesting after 30 days for 11 months.
uint256 constant public TOTAL_VESTING_TIME = 330 days;
address immutable public TO;
uint256 public vestingStartTimestamp;
uint256 public vestingEndTimestamp;
uint256 public totalClaimed;
constructor(address _deltaToken, address _to) {
DELTA_TOKEN = IDeltaToken(_deltaToken);
TO = _to;
}
function initialize() public {
require(vestingStartTimestamp == 0, 'ALREADY_INITIALIZED');
DELTA_TOKEN.transferFrom(msg.sender, address(this), TOTAL_EXPECTED_AMOUNT);
require(DELTA_TOKEN.balanceOf(address(this)) == TOTAL_EXPECTED_AMOUNT, 'INSUFFICIENT_AMOUNT');
// Verify whitelistings
UserInformation memory accountInfo = DELTA_TOKEN.userInformation(address(this));
require(accountInfo.noVestingWhitelisted == true, 'NOT_NOVESTING_WHITELISTED');
require(accountInfo.fullSenderWhitelisted == true, 'NOT_FULLSENDER_WHITELISTED');
// Start vesting after 1 month since we advanced the complete first month
vestingStartTimestamp = block.timestamp + 30 days;
// Vesting ends in 11 months after that
vestingEndTimestamp = vestingStartTimestamp + TOTAL_VESTING_TIME;
// send out the first month right away
DELTA_TOKEN.transfer(TO, INITIAL_CLAIM);
}
function claim() public {
require(msg.sender == TO, 'INVALID_SENDER');
// It should never be possible to transfer more
// than VESTING_AMOUNT (206250 DELTA tokens) from this contract.
require(totalClaimed < VESTING_AMOUNT, 'ALL_CLAIMED');
uint256 claimed = claimable();
DELTA_TOKEN.transfer(TO, claimed);
totalClaimed = totalClaimed.add(claimed);
}
function claimable() public view returns (uint256) {
// Nothing claimable prior to the first month since we send an advance the first
// one and don't report any claimable when it's all claimed already.
// This, to ensure the contract is not used to fullSend arbitrary delta tokens.
if(block.timestamp < vestingStartTimestamp || totalClaimed >= VESTING_AMOUNT) {
return 0;
}
// Vesting has ended, send-out all the balance
if (block.timestamp >= vestingEndTimestamp) {
return DELTA_TOKEN.balanceOf(address(this));
}
uint256 secondsSinceVestingStarted = block.timestamp - vestingStartTimestamp;
return VESTING_AMOUNT.mul(secondsSinceVestingStarted).div(TOTAL_VESTING_TIME).sub(totalClaimed);
}
receive() external payable {
revert();
}
}
// SPDX-License-Identifier: UNLICENSED
// DELTA-BUG-BOUNTY
pragma solidity ^0.7.6;
struct VestingTransaction {
uint256 amount;
uint256 fullVestingTimestamp;
}
struct WalletTotals {
uint256 mature;
uint256 immature;
uint256 total;
}
struct UserInformation {
// This is going to be read from only [0]
uint256 mostMatureTxIndex;
uint256 lastInTxIndex;
uint256 maturedBalance;
uint256 maxBalance;
bool fullSenderWhitelisted;
// Note that recieving immature balances doesnt mean they recieve them fully vested just that senders can do it
bool immatureReceiverWhitelisted;
bool noVestingWhitelisted;
}
struct UserInformationLite {
uint256 maturedBalance;
uint256 maxBalance;
uint256 mostMatureTxIndex;
uint256 lastInTxIndex;
}
struct VestingTransactionDetailed {
uint256 amount;
uint256 fullVestingTimestamp;
// uint256 percentVestedE4;
uint256 mature;
uint256 immature;
}
uint256 constant QTY_EPOCHS = 7;
uint256 constant SECONDS_PER_EPOCH = 172800; // About 2days
uint256 constant FULL_EPOCH_TIME = SECONDS_PER_EPOCH * QTY_EPOCHS;
// Precision Multiplier -- this many zeros (23) seems to get all the precision needed for all 18 decimals to be only off by a max of 1 unit
uint256 constant PM = 1e23;
// 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: UNLICENSED
pragma experimental ABIEncoderV2;
pragma solidity ^0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../common/OVLTokenTypes.sol";
interface IDeltaToken is IERC20 {
function vestingTransactions(address, uint256) external view returns (VestingTransaction memory);
function getUserInfo(address) external view returns (UserInformationLite memory);
function getMatureBalance(address, uint256) external view returns (uint256);
function liquidityRebasingPermitted() external view returns (bool);
function lpTokensInPair() external view returns (uint256);
function governance() external view returns (address);
function performLiquidityRebasing() external;
function distributor() external view returns (address);
function totalsForWallet(address ) external view returns (WalletTotals memory totals);
function adjustBalanceOfNoVestingAccount(address, uint256,bool) external;
function userInformation(address user) external view returns (UserInformation memory);
}
// 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);
}
| @dev first month is paid out at the start @dev 11 months since we advance the first month so it starts vesting after 30 days for 11 months. | constructor(address _deltaToken, address _to) {
DELTA_TOKEN = IDeltaToken(_deltaToken);
TO = _to;
}
| 13,071,478 | [
1,
3645,
3138,
353,
30591,
596,
622,
326,
787,
225,
4648,
8846,
3241,
732,
8312,
326,
1122,
3138,
1427,
518,
2542,
331,
10100,
1839,
5196,
4681,
364,
4648,
8846,
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
] | [
1,
1,
1,
1,
1,
1,
1,
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,
3885,
12,
2867,
389,
9878,
1345,
16,
1758,
389,
869,
13,
288,
203,
3639,
2030,
48,
9833,
67,
8412,
273,
1599,
8967,
1345,
24899,
9878,
1345,
1769,
203,
3639,
8493,
273,
389,
869,
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
] |
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// FantomDebtStorage implements a debt storage used
// by the Fantom DeFi contract to track debt accounts balances and value.
contract FantomDebtStorage {
// define used libs
using SafeMath for uint256;
using Address for address;
using SafeERC20 for ERC20;
// -------------------------------------------------------------
// Debt related state variables
// -------------------------------------------------------------
// _debtBalance tracks user => token => debt amount relationship
mapping(address => mapping(address => uint256)) public debtBalance;
// _debtTotalBalance keeps track of the total debt balances
// of all the debt tokens registered in the storage
// mapping: token => debt amount
mapping(address => uint256) public debtTotalBalance;
// _debtTokens represents the list of all collateral tokens
// registered with the collateral storage.
address[] public debtTokens;
// -------------------------------------------------------------
// Debt value related calculations
// -------------------------------------------------------------
// tokenValue (abstract) returns the value of the given amount of the token specified.
function tokenValue(address _token, uint256 _amount) public view returns (uint256);
// debtTotal returns the total value of all the debt tokens
// registered inside the storage.
function debtTotal() public view returns (uint256 value) {
// loop all registered debt tokens
for (uint i = 0; i < debtTokens.length; i++) {
// advance the total value by the current debt balance token value
value = value.add(tokenValue(debtTokens[i], debtTotalBalance[debtTokens[i]]));
}
// keep the value
return value;
}
// debtValueOf returns the current debt balance of the specified account.
function debtValueOf(address _account) public view returns (uint256 value) {
// loop all registered debt tokens
for (uint i = 0; i < debtTokens.length; i++) {
// advance the value by the current debt balance tokens on the account token scanned
if (0 < debtBalance[_account][debtTokens[i]]) {
value = value.add(tokenValue(debtTokens[i], debtBalance[_account][debtTokens[i]]));
}
}
return value;
}
// -------------------------------------------------------------
// Debt state update functions
// -------------------------------------------------------------
// debtAdd adds specified amount of tokens to given account
// debt (e.g. borrow/mint) and updates the total supply references.
function debtAdd(address _account, address _token, uint256 _amount) internal {
// update the collateral balance of the account
debtBalance[_account][_token] = debtBalance[_account][_token].add(_amount);
// update the total debt balance
debtTotalBalance[_token] = debtTotalBalance[_token].add(_amount);
// make sure the token is registered
debtEnrollToken(_token);
}
// debtSub removes specified amount of tokens from given account
// debt (e.g. repay) and updates the total supply references.
function debtSub(address _account, address _token, uint256 _amount) internal {
// update the debt balance of the account
debtBalance[_account][_token] = debtBalance[_account][_token].sub(_amount);
// update the total debt balance
debtTotalBalance[_token] = debtTotalBalance[_token].sub(_amount);
}
// -------------------------------------------------------------
// Debt related utility functions
// -------------------------------------------------------------
// debtEnrollToken ensures the specified token is in the list
// of debt tokens registered with the protocol.
function debtEnrollToken(address _token) internal {
bool found = false;
// loop the current list and try to find the token
for (uint256 i = 0; i < debtTokens.length; i++) {
if (debtTokens[i] == _token) {
found = true;
break;
}
}
// add the token to the list if not found
if (!found) {
debtTokens.push(_token);
}
}
// debtTokensCount returns the number of tokens enrolled
// to the debt list.
function debtTokensCount() public view returns (uint256) {
// return the current collateral array length
return debtTokens.length;
}
} | loop all registered debt tokens advance the total value by the current debt balance token value | function debtTotal() public view returns (uint256 value) {
for (uint i = 0; i < debtTokens.length; i++) {
value = value.add(tokenValue(debtTokens[i], debtTotalBalance[debtTokens[i]]));
}
}
| 12,765,223 | [
1,
6498,
777,
4104,
18202,
88,
2430,
8312,
326,
2078,
460,
635,
326,
783,
18202,
88,
11013,
1147,
460,
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
] | [
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,
0,
0
] | [
1,
565,
445,
18202,
88,
5269,
1435,
1071,
1476,
1135,
261,
11890,
5034,
460,
13,
288,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
18202,
88,
5157,
18,
2469,
31,
277,
27245,
288,
203,
5411,
460,
273,
460,
18,
1289,
12,
2316,
620,
12,
323,
23602,
5157,
63,
77,
6487,
18202,
88,
5269,
13937,
63,
323,
23602,
5157,
63,
77,
65,
5717,
1769,
203,
3639,
289,
203,
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
] |
//Address: 0x8103864de9cbbd6165b62c0ac8252d6d9f94bc32
//Contract name: GoCryptobotCore
//Balance: 0 Ether
//Verification Date: 5/12/2018
//Transacion Count: 259
// CODE STARTS HERE
pragma solidity ^0.4.18;
contract GoCryptobotAccessControl {
address public owner;
address public operator;
bool public paused;
modifier onlyOwner() {require(msg.sender == owner); _;}
modifier onlyOperator() {require(msg.sender == operator); _;}
modifier onlyOwnerOrOperator() {require(msg.sender == owner || msg.sender == operator); _;}
modifier whenPaused() {require(paused); _;}
modifier whenNotPaused() {require(!paused); _;}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
function transferOperator(address newOperator) public onlyOwner {
require(newOperator != address(0));
operator = newOperator;
}
function pause() public onlyOwnerOrOperator whenNotPaused {
paused = true;
}
function unpause() public onlyOwner whenPaused {
paused = false;
}
}
contract GoCryptobotRandom is GoCryptobotAccessControl {
uint commitmentNumber;
bytes32 randomBytes;
function commitment() public onlyOperator {
commitmentNumber = block.number;
}
function _initRandom() internal {
require(commitmentNumber < block.number);
if (commitmentNumber < block.number - 255) {
randomBytes = block.blockhash(block.number - 1);
} else {
randomBytes = block.blockhash(commitmentNumber);
}
}
function _shuffle(uint8[] deck) internal {
require(deck.length < 256);
uint8 deckLength = uint8(deck.length);
uint8 random;
for (uint8 i = 0; i < deckLength; i++) {
if (i % 32 == 0) {
randomBytes = keccak256(randomBytes);
}
random = uint8(randomBytes[i % 32]) % (deckLength - i);
if (random != deckLength - 1 - i) {
deck[random] ^= deck[deckLength - 1 - i];
deck[deckLength - 1 - i] ^= deck[random];
deck[random] ^= deck[deckLength - 1 - i];
}
}
}
function _random256() internal returns(uint256) {
randomBytes = keccak256(randomBytes);
return uint256(randomBytes);
}
}
contract GoCryptobotScore is GoCryptobotRandom {
// A part's skill consists of color and level. (Total 2 bytes)
// 1 2
// Skill
// +---+---+
// | C | L +
// +---+---+
//
// C = Color, 0 ~ 4.
// L = Level, 0 ~ 8.
//
uint256 constant PART_SKILL_SIZE = 2;
// A part consists of level and 3 skills. (Total 7 bytes)
// 1 2 3 4 5 6 7
// Part
// +---+---+---+---+---+---+---+
// | L | Skill | Skill | Skill |
// +---+---+---+---+---+---+---+
//
// L = Level, 1 ~ 50.
//
// A part doesn't contains color because individual color doesn't affect to
// the score, but it is used to calculate player's theme color.
//
uint256 constant PART_BASE_SIZE = 1;
uint256 constant PART_SIZE = PART_BASE_SIZE + 3 * PART_SKILL_SIZE;
// A player consists of theme effect and 4 parts. (Total 29 bytes)
// 1 2 3 4 5 6 7
// Player
// +---+
// | C |
// +---+---+---+---+---+---+---+
// | HEAD PART |
// +---+---+---+---+---+---+---+
// | BODY PART |
// +---+---+---+---+---+---+---+
// | LEGS PART |
// +---+---+---+---+---+---+---+
// | BOOSTER PART |
// +---+---+---+---+---+---+---+
//
// C = Whether player's theme effect is enabled or not, 1 or 0.
//
// The theme effect is set to 1 iff the theme of each part are identical.
//
uint256 constant PLAYER_BASE_SIZE = 1;
uint256 constant PLAYER_SIZE = PLAYER_BASE_SIZE + PART_SIZE * 4;
enum PartType {HEAD, BODY, LEGS, BOOSTER}
enum EventType {BOWLING, HANGING, SPRINT, HIGH_JUMP}
enum EventColor {NONE, YELLOW, BLUE, GREEN, RED}
function _getPartLevel(bytes data, uint partOffset) internal pure returns(uint8) {
return uint8(data[partOffset + 0]);
}
// NOTE: _getPartSkillColor is called up to 128 * 4 * 3 times. Explicit
// conversion to EventColor could be costful.
function _getPartSkillColor(bytes data, uint partOffset, uint skillIndex) internal pure returns(byte) {
return data[partOffset + PART_BASE_SIZE + (skillIndex * PART_SKILL_SIZE) + 0];
}
function _getPartSkillLevel(bytes data, uint partOffset, uint skillIndex) internal pure returns(uint8) {
return uint8(data[partOffset + PART_BASE_SIZE + (skillIndex * PART_SKILL_SIZE) + 1]);
}
function _getPlayerThemeEffect(bytes data, uint playerOffset) internal pure returns(byte) {
return data[playerOffset + 0];
}
function _getPlayerEventScore(bytes data, uint playerIndex, EventType eventType, EventColor _eventMajorColor, EventColor _eventMinorColor) internal pure returns(uint) {
uint partOffset = (PLAYER_SIZE * playerIndex) + PLAYER_BASE_SIZE + (uint256(eventType) * PART_SIZE);
uint level = _getPartLevel(data, partOffset);
uint majorSkillSum = 0;
uint minorSkillSum = 0;
byte eventMajorColor = byte(uint8(_eventMajorColor));
byte eventMinorColor = byte(uint8(_eventMinorColor));
for (uint i = 0; i < 3; i++) {
byte skillColor = _getPartSkillColor(data, partOffset, i);
if (skillColor == eventMajorColor) {
majorSkillSum += _getPartSkillLevel(data, partOffset, i);
} else if (skillColor == eventMinorColor) {
minorSkillSum += _getPartSkillLevel(data, partOffset, i);
}
}
byte playerThemeEffect = _getPlayerThemeEffect(data, PLAYER_SIZE * playerIndex);
if (playerThemeEffect != 0) {
return level + (majorSkillSum * 4) + (minorSkillSum * 2);
} else {
return level + (majorSkillSum * 3) + (minorSkillSum * 1);
}
}
}
contract GoCryptobotRounds is GoCryptobotScore {
event RoundFinished(EventType eventType, EventColor eventMajorColor, EventColor eventMinorColor, uint scoreA, uint scoreB, uint scoreC, uint scoreD);
event AllFinished(uint scoreA, uint scoreB, uint scoreC, uint scoreD);
event WinnerTeam(uint8[4] candidates, uint8 winner);
function run(bytes playerData, uint8[4] eventTypes, uint8[2][4] eventColors) public onlyOperator {
require(playerData.length == 128 * PLAYER_SIZE);
_initRandom();
uint8[] memory colorSelection = new uint8[](8);
colorSelection[0] = 0;
colorSelection[1] = 1;
colorSelection[2] = 0;
colorSelection[3] = 1;
colorSelection[4] = 0;
colorSelection[5] = 1;
colorSelection[6] = 0;
colorSelection[7] = 1;
_shuffle(colorSelection);
uint[4] memory totalScores;
for (uint8 i = 0; i < 4; i++) {
uint8 majorColor = eventColors[i][colorSelection[i]];
uint8 minorColor = eventColors[i][colorSelection[i]^1];
uint[4] memory roundScores = _round(playerData, EventType(eventTypes[i]), EventColor(majorColor), EventColor(minorColor));
totalScores[0] += roundScores[0];
totalScores[1] += roundScores[1];
totalScores[2] += roundScores[2];
totalScores[3] += roundScores[3];
}
AllFinished(totalScores[0], totalScores[1], totalScores[2], totalScores[3]);
uint maxScore;
uint maxCount;
uint8[4] memory candidates;
for (i = 0; i < 4; i++) {
if (maxScore < totalScores[i]) {
maxScore = totalScores[i];
maxCount = 0;
candidates[maxCount++] = i + 1;
} else if (maxScore == totalScores[i]) {
candidates[maxCount++] = i + 1;
}
}
assert(maxCount > 0);
if (maxCount == 1) {
WinnerTeam(candidates, candidates[0]);
} else {
WinnerTeam(candidates, candidates[_random256() % maxCount]);
}
}
function _round(bytes memory playerData, EventType eventType, EventColor eventMajorColor, EventColor eventMinorColor) internal returns(uint[4]) {
uint numOfPlayers = playerData.length / PLAYER_SIZE;
uint[4] memory scores;
for (uint i = 0; i < numOfPlayers; i++) {
scores[i / (numOfPlayers / 4)] += _getPlayerEventScore(playerData, i, eventType, eventMajorColor, eventMinorColor);
}
RoundFinished(eventType, eventMajorColor, eventMinorColor, scores[0], scores[1], scores[2], scores[3]);
return scores;
}
}
contract GoCryptobotCore is GoCryptobotRounds {
function GoCryptobotCore() public {
paused = false;
owner = msg.sender;
operator = msg.sender;
}
}
| NOTE: _getPartSkillColor is called up to 128 * 4 * 3 times. Explicit conversion to EventColor could be costful. | function _getPartSkillColor(bytes data, uint partOffset, uint skillIndex) internal pure returns(byte) {
return data[partOffset + PART_BASE_SIZE + (skillIndex * PART_SKILL_SIZE) + 0];
}
| 2,562,426 | [
1,
17857,
30,
389,
588,
1988,
9030,
2957,
353,
2566,
731,
358,
8038,
225,
1059,
225,
890,
4124,
18,
24321,
4105,
358,
2587,
2957,
3377,
506,
6991,
2706,
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
] | [
1,
1,
1,
1,
1,
1,
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,
565,
445,
389,
588,
1988,
9030,
2957,
12,
3890,
501,
16,
2254,
1087,
2335,
16,
2254,
15667,
1016,
13,
2713,
16618,
1135,
12,
7229,
13,
288,
203,
3639,
327,
501,
63,
2680,
2335,
397,
20814,
67,
8369,
67,
4574,
397,
261,
7771,
737,
1016,
380,
20814,
67,
11129,
15125,
67,
4574,
13,
397,
374,
15533,
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
] |
./partial_match/1/0xeF8A5A4105194271804033a6bd11E36A4acC6499/sources/standardToken.sol | * @title Pausable token @dev ERC20 with pausable transfers and allowances. Useful if you want to, e.g., stop trades until the end of a crowdsale, or have an emergency switch for freezing all token transfers in the event of a large bug./ | contract ERC20Pausable is Pausable, ERC20 {
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 increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
| 9,281,197 | [
1,
16507,
16665,
1147,
225,
4232,
39,
3462,
598,
6790,
16665,
29375,
471,
1699,
6872,
18,
19256,
309,
1846,
2545,
358,
16,
425,
18,
75,
12990,
2132,
1284,
5489,
3180,
326,
679,
434,
279,
276,
492,
2377,
5349,
16,
578,
1240,
392,
801,
24530,
1620,
364,
4843,
94,
310,
777,
1147,
29375,
316,
326,
871,
434,
279,
7876,
7934,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
4232,
39,
3462,
16507,
16665,
353,
21800,
16665,
16,
4232,
39,
3462,
288,
203,
565,
445,
7412,
12,
2867,
358,
16,
2254,
5034,
460,
13,
1071,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
13866,
12,
869,
16,
460,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
460,
13,
1071,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
13866,
1265,
12,
2080,
16,
358,
16,
460,
1769,
203,
565,
289,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
460,
13,
1071,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
12908,
537,
12,
87,
1302,
264,
16,
460,
1769,
203,
565,
289,
203,
203,
565,
445,
10929,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
5034,
3096,
620,
13,
1071,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
267,
11908,
7009,
1359,
12,
87,
1302,
264,
16,
3096,
620,
1769,
203,
565,
289,
203,
203,
565,
445,
20467,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
5034,
10418,
329,
620,
13,
1071,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
323,
11908,
7009,
1359,
12,
87,
1302,
264,
16,
10418,
329,
620,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
// Utilizes the useful mentions in the article below to address the pesky mint costs
// Credit where credit is due
// =============================================================================
// https://shiny.mirror.xyz/OUampBbIz9ebEicfGnQf5At_ReMHlZy0tB4glb9xQ0E
// =============================================================================
import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // NO MORE NUMERABLES
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Lovely_Raccs is ERC721, Ownable {
// vv Global Variables vv
using Strings for uint256;
// Comes with the gas update
// ====================================
using Counters for Counters.Counter;
Counters.Counter private supply;
// ====================================
string public uriPrefix = ""; // To be updated
string public uriSuffix = ".json";
string public hiddenMetadataUri;
// Does the greed hit?
uint256 public mintCost = 0.03 ether;
uint256 public publicCost = 0.05 ether;
uint256 public maxSupply = 10000; // Has known to show atleast double the amount of '0's in the test environment, uint256 thing?
uint256 public maxMintAmountPerTx = 2;
bool public paused = true;
bool public revealed = false;
constructor() ERC721("Lovely_Raccs", "LR") {
//setHiddenMetadataUri("ipfs://QmRRwj458iG6qTFHGDw9nrBLzKLtBhbM2u1jRBNnfyDyvM/TBR.json"); // Used for hiding the image in the metadata
setRevealed(true);
}
// Custom-made modifier for checking
modifier mintCompliance(uint256 _mintAmount) {
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); // Minting too little or too many
require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); // Supply has enough stock for current mint transaction
_;
}
function totalSupply() public view returns (uint256) { return supply.current(); } // Current total supply of tokens
function WLmint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { // Used for whitelist minting
require(!paused, "The contract is paused!");
require(msg.value >= mintCost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount); // Helper function below
}
function publicMint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { // Used for public minting
require(!paused, "The contract is paused!");
require(msg.value >= publicCost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount);
}
// Mints the token to a specific address (as opposed to the currently connected one)
function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); }
// Grabs the wallet and wallet information of the owner and their tokens
function walletOfOwner(address _owner) public view returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
// Returns the given tokens URI address
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory)
{
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
if (revealed == false) { return hiddenMetadataUri; }
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : "";
}
function setRevealed(bool _state) public onlyOwner { revealed = _state; } // Hide/Unhide the metadata
function setMintCost(uint256 _cost) public onlyOwner { mintCost = _cost; } // Takes wei instead of ether V. IMPORTANT
function setPublicCost(uint256 _cost) public onlyOwner { publicCost = _cost; } // Takes wei instead of ether V. IMPORTANT
function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; }
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; }
function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } // ipfs://<prefix>/<suffix>
function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; }
function setPaused(bool _state) public onlyOwner { paused = _state; } // Sets the pause state of the contract
function withdraw() public onlyOwner {
// This is an example split for 5% of the initial sale (using my own address).
// =============================================================================
//(bool hs, ) = payable(0xdFecCC7506725439a862AEfCF134C0B2a345AE5a).call{value: address(this).balance * 5 / 100}("");
//require(hs);
// =============================================================================
// This will transfer the remaining contract balance to the owner.
// Do not remove this otherwise your funds will be stuck in the ether.. literally. IMPORTANT.
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
// Uses the OpenZeppelin minting method for safer transactions
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current()); }
}
// Returns the base contract prefix
function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; }
} | Returns the given tokens URI address | {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : "";
if (revealed == false) { return hiddenMetadataUri; }
}
| 1,830,775 | [
1,
1356,
326,
864,
2430,
3699,
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,
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,
225,
288,
203,
565,
2583,
24899,
1808,
24899,
2316,
548,
3631,
315,
654,
39,
27,
5340,
2277,
30,
3699,
843,
364,
1661,
19041,
1147,
8863,
203,
203,
203,
565,
533,
3778,
783,
2171,
3098,
273,
389,
1969,
3098,
5621,
203,
565,
327,
1731,
12,
2972,
2171,
3098,
2934,
2469,
405,
374,
692,
533,
12,
21457,
18,
3015,
4420,
329,
12,
2972,
2171,
3098,
16,
389,
2316,
548,
18,
10492,
9334,
2003,
5791,
3719,
294,
1408,
31,
203,
565,
309,
261,
266,
537,
18931,
422,
629,
13,
288,
327,
5949,
2277,
3006,
31,
289,
203,
225,
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
] |
/**
* @author Valentin Mueller <https://github.com/ValentinFFM>
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;
// Experimental function is necessary to allow mappings with structs.
pragma experimental ABIEncoderV2;
/**
The Smart Contract User is responsible for storing the information of all users.
Furthermore it provides all necessary functions to interact with users.
*/
contract User {
address public verifying_institution;
// Assigns the creator of the smart contract as verifying institution.
constructor () public {
verifying_institution = msg.sender;
}
// Defining struct that contains all variables that are needed for a insured.
struct Insured {
string surname;
string name;
string street;
string street_number;
uint post_code;
string city;
string birth_date;
string insurance;
uint insurance_number;
uint insured_number;
uint insured_status;
bool verified;
}
// Defining struct that contains all variables that are needed for a physician.
struct Physician {
string job_title;
string surname;
string name;
uint physician_number;
string street;
string street_number;
uint post_code;
string city;
string telephone_number;
uint business_number;
bool verified;
}
// Defining struct that contains all variables that are needed for a pharmacist.
struct Pharmacist {
uint pharmacy_number;
string name;
bool verified;
}
// For every user group the public keys of the users are mapped to the corresponding user struct.
mapping(address => Insured) public insureds;
mapping(address => Physician) public physicians;
mapping(address => Pharmacist) public pharmacists;
function addNewInsured(Insured memory insured_) public{
insureds[msg.sender] = Insured(insured_.surname, insured_.name, insured_.street, insured_.street_number, insured_.post_code, insured_.city, insured_.birth_date, insured_.insurance, insured_.insurance_number, insured_.insured_number, insured_.insured_status, false);
}
function addNewPhysician(Physician memory physician_) public{
physicians[msg.sender] = Physician(physician_.job_title, physician_.surname, physician_.name, physician_.physician_number, physician_.street, physician_.street_number, physician_.post_code, physician_.city, physician_.telephone_number, physician_.business_number, false);
}
function addNewPharmacist(Pharmacist memory pharmacist_) public{
pharmacists[msg.sender] = Pharmacist(pharmacist_.pharmacy_number, pharmacist_.name, false);
}
function verifyInsured(address public_key) public returns (bool){
require(msg.sender == verifying_institution, "Only the verify institution has the right to verify insured!");
require(insureds[public_key].insured_number > 0, "No insured exists under this address!");
insureds[public_key].verified = true;
}
function verifyPhysician(address public_key) public returns (bool){
require(msg.sender == verifying_institution, "Only the verify institution has the right to verify physician!");
require(physicians[public_key].physician_number > 0, "No physician exists under this address!");
physicians[public_key].verified = true;
}
function verifyPharmacist(address public_key) public returns (bool){
require(msg.sender == verifying_institution, "Only the verify institution has the right to verify pharmacist!");
require(pharmacists[public_key].pharmacy_number > 0, "No pharmacist exists under this address!");
pharmacists[public_key].verified = true;
}
function getInsured(address public_key) public view returns(Insured memory){
if(insureds[public_key].insured_number > 0){
return insureds[public_key];
}
}
function getPhysician(address public_key) public view returns(Physician memory){
if(physicians[public_key].physician_number > 0){
return physicians[public_key];
}
}
function getPharmacist(address public_key) public view returns(Pharmacist memory){
if(pharmacists[public_key].pharmacy_number > 0){
return pharmacists[public_key];
}
}
// Returns true, if the user exists.
function checkExistence(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number >0){
return true;
} else {
return false;
}
} else if (keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('physician'))){
if(physicians[public_key].physician_number >0){
return true;
} else {
return false;
}
} else if (keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('pharmacist'))){
if(pharmacists[public_key].pharmacy_number >0){
return true;
} else {
return false;
}
} else if (keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('verifying_institution'))){
if(verifying_institution == public_key){
return true;
} else {
return false;
}
}
}
// Returns true, if the user exists and is verified by the verifying institution.
function checkVerification(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number > 0 && insureds[public_key].verified == true){
return true;
} else {
return false;
}
} else if (keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('physician'))){
if(physicians[public_key].physician_number > 0 && physicians[public_key].verified == true){
return true;
} else {
return false;
}
} else if (keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('pharmacist'))){
if(pharmacists[public_key].pharmacy_number >0 && pharmacists[public_key].verified == true){
return true;
} else {
return false;
}
} else if (keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('verifying_institution'))){
if(verifying_institution == public_key){
return true;
} else {
return false;
}
}
}
} | / Assigns the creator of the smart contract as verifying institution. | contract User {
address public verifying_institution;
pragma solidity >=0.4.21 <0.7.0;
pragma experimental ABIEncoderV2;
The Smart Contract User is responsible for storing the information of all users.
Furthermore it provides all necessary functions to interact with users.
constructor () public {
verifying_institution = msg.sender;
}
struct Insured {
string surname;
string name;
string street;
string street_number;
uint post_code;
string city;
string birth_date;
string insurance;
uint insurance_number;
uint insured_number;
uint insured_status;
bool verified;
}
struct Physician {
string job_title;
string surname;
string name;
uint physician_number;
string street;
string street_number;
uint post_code;
string city;
string telephone_number;
uint business_number;
bool verified;
}
struct Pharmacist {
uint pharmacy_number;
string name;
bool verified;
}
mapping(address => Physician) public physicians;
mapping(address => Pharmacist) public pharmacists;
mapping(address => Insured) public insureds;
function addNewInsured(Insured memory insured_) public{
insureds[msg.sender] = Insured(insured_.surname, insured_.name, insured_.street, insured_.street_number, insured_.post_code, insured_.city, insured_.birth_date, insured_.insurance, insured_.insurance_number, insured_.insured_number, insured_.insured_status, false);
}
function addNewPhysician(Physician memory physician_) public{
physicians[msg.sender] = Physician(physician_.job_title, physician_.surname, physician_.name, physician_.physician_number, physician_.street, physician_.street_number, physician_.post_code, physician_.city, physician_.telephone_number, physician_.business_number, false);
}
function addNewPharmacist(Pharmacist memory pharmacist_) public{
pharmacists[msg.sender] = Pharmacist(pharmacist_.pharmacy_number, pharmacist_.name, false);
}
function verifyInsured(address public_key) public returns (bool){
require(msg.sender == verifying_institution, "Only the verify institution has the right to verify insured!");
require(insureds[public_key].insured_number > 0, "No insured exists under this address!");
insureds[public_key].verified = true;
}
function verifyPhysician(address public_key) public returns (bool){
require(msg.sender == verifying_institution, "Only the verify institution has the right to verify physician!");
require(physicians[public_key].physician_number > 0, "No physician exists under this address!");
physicians[public_key].verified = true;
}
function verifyPharmacist(address public_key) public returns (bool){
require(msg.sender == verifying_institution, "Only the verify institution has the right to verify pharmacist!");
require(pharmacists[public_key].pharmacy_number > 0, "No pharmacist exists under this address!");
pharmacists[public_key].verified = true;
}
function getInsured(address public_key) public view returns(Insured memory){
if(insureds[public_key].insured_number > 0){
return insureds[public_key];
}
}
function getInsured(address public_key) public view returns(Insured memory){
if(insureds[public_key].insured_number > 0){
return insureds[public_key];
}
}
function getPhysician(address public_key) public view returns(Physician memory){
if(physicians[public_key].physician_number > 0){
return physicians[public_key];
}
}
function getPhysician(address public_key) public view returns(Physician memory){
if(physicians[public_key].physician_number > 0){
return physicians[public_key];
}
}
function getPharmacist(address public_key) public view returns(Pharmacist memory){
if(pharmacists[public_key].pharmacy_number > 0){
return pharmacists[public_key];
}
}
function getPharmacist(address public_key) public view returns(Pharmacist memory){
if(pharmacists[public_key].pharmacy_number > 0){
return pharmacists[public_key];
}
}
function checkExistence(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number >0){
return true;
return false;
}
if(physicians[public_key].physician_number >0){
return true;
return false;
}
if(pharmacists[public_key].pharmacy_number >0){
return true;
return false;
}
if(verifying_institution == public_key){
return true;
return false;
}
}
}
function checkExistence(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number >0){
return true;
return false;
}
if(physicians[public_key].physician_number >0){
return true;
return false;
}
if(pharmacists[public_key].pharmacy_number >0){
return true;
return false;
}
if(verifying_institution == public_key){
return true;
return false;
}
}
}
function checkExistence(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number >0){
return true;
return false;
}
if(physicians[public_key].physician_number >0){
return true;
return false;
}
if(pharmacists[public_key].pharmacy_number >0){
return true;
return false;
}
if(verifying_institution == public_key){
return true;
return false;
}
}
}
} else {
} else if (keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('physician'))){
function checkExistence(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number >0){
return true;
return false;
}
if(physicians[public_key].physician_number >0){
return true;
return false;
}
if(pharmacists[public_key].pharmacy_number >0){
return true;
return false;
}
if(verifying_institution == public_key){
return true;
return false;
}
}
}
} else {
} else if (keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('pharmacist'))){
function checkExistence(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number >0){
return true;
return false;
}
if(physicians[public_key].physician_number >0){
return true;
return false;
}
if(pharmacists[public_key].pharmacy_number >0){
return true;
return false;
}
if(verifying_institution == public_key){
return true;
return false;
}
}
}
} else {
} else if (keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('verifying_institution'))){
function checkExistence(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number >0){
return true;
return false;
}
if(physicians[public_key].physician_number >0){
return true;
return false;
}
if(pharmacists[public_key].pharmacy_number >0){
return true;
return false;
}
if(verifying_institution == public_key){
return true;
return false;
}
}
}
} else {
function checkVerification(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number > 0 && insureds[public_key].verified == true){
return true;
return false;
}
if(physicians[public_key].physician_number > 0 && physicians[public_key].verified == true){
return true;
return false;
}
if(pharmacists[public_key].pharmacy_number >0 && pharmacists[public_key].verified == true){
return true;
return false;
}
if(verifying_institution == public_key){
return true;
return false;
}
}
}
function checkVerification(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number > 0 && insureds[public_key].verified == true){
return true;
return false;
}
if(physicians[public_key].physician_number > 0 && physicians[public_key].verified == true){
return true;
return false;
}
if(pharmacists[public_key].pharmacy_number >0 && pharmacists[public_key].verified == true){
return true;
return false;
}
if(verifying_institution == public_key){
return true;
return false;
}
}
}
function checkVerification(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number > 0 && insureds[public_key].verified == true){
return true;
return false;
}
if(physicians[public_key].physician_number > 0 && physicians[public_key].verified == true){
return true;
return false;
}
if(pharmacists[public_key].pharmacy_number >0 && pharmacists[public_key].verified == true){
return true;
return false;
}
if(verifying_institution == public_key){
return true;
return false;
}
}
}
} else {
} else if (keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('physician'))){
function checkVerification(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number > 0 && insureds[public_key].verified == true){
return true;
return false;
}
if(physicians[public_key].physician_number > 0 && physicians[public_key].verified == true){
return true;
return false;
}
if(pharmacists[public_key].pharmacy_number >0 && pharmacists[public_key].verified == true){
return true;
return false;
}
if(verifying_institution == public_key){
return true;
return false;
}
}
}
} else {
} else if (keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('pharmacist'))){
function checkVerification(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number > 0 && insureds[public_key].verified == true){
return true;
return false;
}
if(physicians[public_key].physician_number > 0 && physicians[public_key].verified == true){
return true;
return false;
}
if(pharmacists[public_key].pharmacy_number >0 && pharmacists[public_key].verified == true){
return true;
return false;
}
if(verifying_institution == public_key){
return true;
return false;
}
}
}
} else {
} else if (keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('verifying_institution'))){
function checkVerification(string memory role, address public_key) public view returns (bool){
if(keccak256(abi.encodePacked(role)) == keccak256(abi.encodePacked('insured'))){
if(insureds[public_key].insured_number > 0 && insureds[public_key].verified == true){
return true;
return false;
}
if(physicians[public_key].physician_number > 0 && physicians[public_key].verified == true){
return true;
return false;
}
if(pharmacists[public_key].pharmacy_number >0 && pharmacists[public_key].verified == true){
return true;
return false;
}
if(verifying_institution == public_key){
return true;
return false;
}
}
}
} else {
} | 12,904,784 | [
1,
19,
12093,
87,
326,
11784,
434,
326,
13706,
6835,
487,
3929,
310,
1804,
305,
1421,
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
] | [
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,
16351,
2177,
288,
203,
203,
565,
1758,
1071,
3929,
310,
67,
267,
14278,
31,
203,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
24,
18,
5340,
411,
20,
18,
27,
18,
20,
31,
203,
683,
9454,
23070,
10336,
45,
7204,
58,
22,
31,
203,
565,
1021,
19656,
13456,
2177,
353,
14549,
364,
15729,
326,
1779,
434,
777,
3677,
18,
203,
565,
478,
295,
451,
1035,
479,
518,
8121,
777,
4573,
4186,
358,
16592,
598,
3677,
18,
203,
565,
3885,
1832,
1071,
288,
203,
3639,
3929,
310,
67,
267,
14278,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
1958,
657,
2055,
72,
288,
203,
3639,
533,
17007,
31,
203,
3639,
533,
508,
31,
203,
3639,
533,
19382,
31,
203,
3639,
533,
19382,
67,
2696,
31,
203,
3639,
2254,
1603,
67,
710,
31,
203,
3639,
533,
12797,
31,
203,
203,
3639,
533,
17057,
67,
712,
31,
203,
203,
3639,
533,
2763,
295,
1359,
31,
203,
3639,
2254,
2763,
295,
1359,
67,
2696,
31,
203,
3639,
2254,
316,
2055,
72,
67,
2696,
31,
203,
3639,
2254,
316,
2055,
72,
67,
2327,
31,
203,
203,
3639,
1426,
13808,
31,
203,
565,
289,
203,
203,
565,
1958,
4360,
1900,
335,
2779,
288,
203,
3639,
533,
1719,
67,
2649,
31,
203,
3639,
533,
17007,
31,
203,
3639,
533,
508,
31,
203,
3639,
2254,
24758,
335,
2779,
67,
2696,
31,
203,
203,
3639,
533,
19382,
31,
203,
3639,
533,
19382,
67,
2696,
31,
203,
3639,
2254,
1603,
67,
710,
31,
203,
3639,
533,
12797,
31,
203,
3639,
2
] |
./partial_match/1/0xb493E63f3b20323177ED08F64b080c282d58C04d/sources/ALIEN.sol | set as marketing wallet
| marketingWallet = address(0x6bA14B0090deb4c1133C2D8c5E9EF2E1EF399924); | 3,906,881 | [
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,
26,
70,
37,
3461,
38,
713,
9349,
31888,
24,
71,
2499,
3707,
39,
22,
40,
28,
71,
25,
41,
29,
26897,
22,
41,
21,
26897,
23,
11984,
3247,
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
] |
./partial_match/4/0x80429Fe7F4756Ad8C2A66cCC643F9B4940642183/sources/uni.sol | constructor(address _coaAddress, address _WETH) public { coaAddress = _coaAddress; WETH = _WETH; } | contract COA_TO_UNI {
address constant coaAddress = 0xB374E5a7481d73B589Be9e12afB42658704cD28b;
address constant WETH = 0xc778417E063141139Fce010982780140Aa0cD5Ab;
mapping (address => uint) balance;
event UniSwapResult(
uint256 amountCOA,
uint256 amountETH,
uint256 liquidity
);
UniswapRouterV2 public constant UNISWAP_ROUTER = UniswapRouterV2(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
IERC20 public Coin = IERC20(coaAddress);
function getCoin(
) public pure returns (address) {
return coaAddress;
}
function getWETH(
) public pure returns (address) {
return WETH;
}
function withdrawBalance() public {
msg.sender.transfer(address(this).balance);
}
function accept() external payable {
require(msg.value >0);
balance[msg.sender] += msg.value;
}
function flush_UNI(uint256 coin_amount)
payable external
{
require(coin_amount>0,"the Amount is ZERO");
require(msg.value>0,"ETH amount to small");
Coin.mint(address(this), coin_amount);
Coin.approve(
address(UNISWAP_ROUTER), coin_amount
);
(
uint256 amountCOA,
uint256 amountETH,
uint256 liquidity
) =
address(Coin),
coin_amount,
0,
0,
address(0x0),
block.timestamp + 2 hours
);
emit UniSwapResult(
amountCOA, amountETH, liquidity
);
}
UNISWAP_ROUTER.addLiquidityETH{value: msg.value}(
}
| 8,508,825 | [
1,
12316,
12,
2867,
389,
2894,
69,
1887,
16,
1758,
389,
59,
1584,
44,
13,
1071,
225,
288,
5411,
1825,
69,
1887,
273,
389,
2894,
69,
1887,
31,
5411,
678,
1584,
44,
273,
389,
59,
1584,
44,
31,
377,
289,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
7910,
37,
67,
4296,
67,
10377,
225,
288,
203,
377,
203,
565,
1758,
5381,
1825,
69,
1887,
273,
374,
20029,
23,
5608,
41,
25,
69,
5608,
11861,
72,
9036,
38,
25,
6675,
1919,
29,
73,
2138,
1727,
38,
24,
5558,
8204,
27,
3028,
71,
40,
6030,
70,
31,
203,
565,
1758,
5381,
678,
1584,
44,
273,
374,
6511,
4700,
5193,
4033,
41,
20,
4449,
3461,
2499,
5520,
42,
311,
1611,
5908,
28,
5324,
28,
1611,
7132,
37,
69,
20,
71,
40,
25,
5895,
31,
203,
565,
2874,
261,
2867,
516,
2254,
13,
11013,
31,
203,
377,
203,
565,
871,
1351,
77,
12521,
1253,
12,
203,
1850,
2254,
5034,
225,
3844,
3865,
37,
16,
203,
1850,
2254,
5034,
3844,
1584,
44,
16,
203,
1850,
2254,
5034,
4501,
372,
24237,
203,
565,
11272,
203,
377,
203,
2398,
203,
203,
377,
203,
565,
1351,
291,
91,
438,
8259,
58,
22,
1071,
5381,
5019,
5127,
59,
2203,
67,
1457,
1693,
654,
273,
1351,
291,
91,
438,
8259,
58,
22,
12,
203,
3639,
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,
7010,
565,
11272,
203,
540,
203,
565,
467,
654,
39,
3462,
1071,
28932,
273,
467,
654,
39,
3462,
12,
2894,
69,
1887,
1769,
203,
203,
203,
565,
445,
1927,
885,
12,
7010,
203,
565,
262,
1071,
16618,
1135,
261,
2867,
13,
288,
1377,
203,
3639,
327,
1825,
69,
1887,
31,
7010,
565,
289,
2
] |
./full_match/100/0x13DEFA7de9e68818dbf01d2F532721748464a6Ba/sources/TokenCreation.sol | End of token creation, in Unix time Minimum fueling goal of the token creation, denominated in tokens to be created True if the DAO reached its minimum fueling goal, false otherwise For DAO splits - if privateCreation is 0, then it is a public token creation, otherwise only the address stored in privateCreation is allowed to create tokens hold extra ether which has been sent after the DAO token creation rate has increased tracks the amount of wei given from each contributor (used for refund) This is the constructor: it can not be overloaded so it is commented out function TokenCreation( uint _minTokensTocreate, uint _closingTime, address _privateCreation string _tokenName, string _tokenSymbol, uint _decimalPlaces ); | abstract contract TokenCreationInterface {
uint public closingTime;
uint public minTokensToCreate;
bool public isFueled;
address public privateCreation;
ManagedAccount public extraBalance;
mapping (address => uint256) weiGiven;
function createTokenProxy(address payable _tokenHolder) payable virtual public returns (bool success);
function refund() virtual public;
function divisor() public virtual view returns (uint divisor);
event FuelingToDate(uint value);
event CreatedToken(address indexed to, uint amount);
event Refund(address indexed to, uint value);
This file is part of the DAO.
}
| 14,266,928 | [
1,
1638,
434,
1147,
6710,
16,
316,
9480,
813,
23456,
284,
20317,
310,
17683,
434,
326,
1147,
6710,
16,
10716,
7458,
316,
2430,
358,
506,
2522,
1053,
309,
326,
463,
20463,
8675,
2097,
5224,
284,
20317,
310,
17683,
16,
629,
3541,
2457,
463,
20463,
11019,
300,
309,
3238,
9906,
353,
374,
16,
1508,
518,
353,
279,
1071,
1147,
6710,
16,
3541,
1338,
326,
1758,
4041,
316,
3238,
9906,
353,
2935,
358,
752,
2430,
6887,
2870,
225,
2437,
1492,
711,
2118,
3271,
1839,
326,
463,
20463,
1147,
6710,
4993,
711,
31383,
13933,
326,
3844,
434,
732,
77,
864,
628,
1517,
31123,
261,
3668,
364,
16255,
13,
1220,
353,
326,
3885,
30,
518,
848,
486,
506,
1879,
4230,
1427,
518,
353,
31813,
596,
225,
445,
3155,
9906,
12,
225,
2254,
389,
1154,
5157,
56,
504,
602,
16,
225,
2254,
389,
19506,
950,
16,
225,
1758,
389,
1152,
9906,
225,
533,
389,
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,
17801,
6835,
3155,
9906,
1358,
288,
203,
203,
565,
2254,
1071,
7647,
950,
31,
203,
565,
2254,
1071,
1131,
5157,
774,
1684,
31,
203,
565,
1426,
1071,
17646,
20317,
329,
31,
203,
565,
1758,
1071,
3238,
9906,
31,
203,
565,
10024,
3032,
1071,
2870,
13937,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
732,
77,
6083,
31,
203,
203,
203,
565,
445,
752,
1345,
3886,
12,
2867,
8843,
429,
389,
2316,
6064,
13,
8843,
429,
5024,
1071,
1135,
261,
6430,
2216,
1769,
203,
203,
565,
445,
16255,
1435,
5024,
1071,
31,
203,
203,
565,
445,
15013,
1435,
1071,
5024,
1476,
1135,
261,
11890,
15013,
1769,
203,
203,
565,
871,
478,
20317,
310,
31264,
12,
11890,
460,
1769,
203,
565,
871,
12953,
1345,
12,
2867,
8808,
358,
16,
2254,
3844,
1769,
203,
565,
871,
3941,
1074,
12,
2867,
8808,
358,
16,
2254,
460,
1769,
203,
2503,
585,
353,
1087,
434,
326,
463,
20463,
18,
203,
203,
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
] |
./partial_match/3/0x3629bBa7574AF0289428237F008350724196ba69/sources/TransferRules.sol | * Realization a addresses whitelist/ | contract Whitelist is OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
struct List {
address addr;
bool alsoGradual;
}
struct ListStruct {
EnumerableSetUpgradeable.AddressSet indexes;
mapping(address => List) data;
}
string internal commonGroupName;
mapping(string => ListStruct) list;
modifier onlyWhitelist(string memory groupName) {
require(
list[groupName].indexes.contains(_msgSender()) == true,
"Sender is not in whitelist"
);
_;
}
function __Whitelist_init(
)
internal
initializer
{
commonGroupName = 'common';
__Ownable_init();
}
function whitelistAdd(address[] memory _addresses) public virtual returns (bool success) {
success = _whitelistAdd(commonGroupName, _addresses);
}
function whitelistRemove(address[] memory _addresses) public virtual returns (bool success) {
success = _whitelistRemove(commonGroupName, _addresses);
}
function isWhitelisted(address addr) public virtual view returns (bool result) {
result = _isWhitelisted(commonGroupName, addr);
}
function _whitelistAdd(string memory groupName, address[] memory _addresses) internal returns (bool) {
for (uint i = 0; i < _addresses.length; i++) {
require(_addresses[i] != address(0), "Whitelist: Contains the zero address");
if (list[groupName].indexes.contains(_addresses[i]) == true) {
list[groupName].indexes.add(_addresses[i]);
list[groupName].data[_addresses[i]].addr = _addresses[i];
}
}
return true;
}
function _whitelistAdd(string memory groupName, address[] memory _addresses) internal returns (bool) {
for (uint i = 0; i < _addresses.length; i++) {
require(_addresses[i] != address(0), "Whitelist: Contains the zero address");
if (list[groupName].indexes.contains(_addresses[i]) == true) {
list[groupName].indexes.add(_addresses[i]);
list[groupName].data[_addresses[i]].addr = _addresses[i];
}
}
return true;
}
function _whitelistAdd(string memory groupName, address[] memory _addresses) internal returns (bool) {
for (uint i = 0; i < _addresses.length; i++) {
require(_addresses[i] != address(0), "Whitelist: Contains the zero address");
if (list[groupName].indexes.contains(_addresses[i]) == true) {
list[groupName].indexes.add(_addresses[i]);
list[groupName].data[_addresses[i]].addr = _addresses[i];
}
}
return true;
}
} else {
function _whitelistRemove(string memory groupName, address[] memory _addresses) internal returns (bool) {
for (uint i = 0; i < _addresses.length; i++) {
if (list[groupName].indexes.remove(_addresses[i]) == true) {
delete list[groupName].data[_addresses[i]];
}
}
return true;
}
function _whitelistRemove(string memory groupName, address[] memory _addresses) internal returns (bool) {
for (uint i = 0; i < _addresses.length; i++) {
if (list[groupName].indexes.remove(_addresses[i]) == true) {
delete list[groupName].data[_addresses[i]];
}
}
return true;
}
function _whitelistRemove(string memory groupName, address[] memory _addresses) internal returns (bool) {
for (uint i = 0; i < _addresses.length; i++) {
if (list[groupName].indexes.remove(_addresses[i]) == true) {
delete list[groupName].data[_addresses[i]];
}
}
return true;
}
function _isWhitelisted(string memory groupName, address addr) internal view returns (bool) {
return list[groupName].indexes.contains(addr);
}
}
| 5,257,592 | [
1,
6955,
1588,
279,
6138,
10734,
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,
16351,
3497,
7523,
353,
14223,
6914,
10784,
429,
288,
203,
565,
1450,
14060,
10477,
10784,
429,
364,
2254,
5034,
31,
203,
565,
1450,
6057,
25121,
694,
10784,
429,
364,
6057,
25121,
694,
10784,
429,
18,
1887,
694,
31,
203,
377,
203,
203,
565,
1958,
987,
288,
203,
3639,
1758,
3091,
31,
203,
3639,
1426,
2546,
30420,
1462,
31,
203,
565,
289,
203,
565,
1958,
987,
3823,
288,
203,
3639,
6057,
25121,
694,
10784,
429,
18,
1887,
694,
5596,
31,
203,
3639,
2874,
12,
2867,
516,
987,
13,
501,
31,
203,
565,
289,
203,
377,
203,
565,
533,
2713,
2975,
3943,
31,
203,
377,
203,
565,
2874,
12,
1080,
516,
987,
3823,
13,
666,
31,
203,
203,
565,
9606,
1338,
18927,
12,
1080,
3778,
11619,
13,
288,
203,
3639,
2583,
12,
203,
5411,
666,
63,
1655,
461,
8009,
11265,
18,
12298,
24899,
3576,
12021,
10756,
422,
638,
16,
7010,
5411,
315,
12021,
353,
486,
316,
10734,
6,
203,
3639,
11272,
203,
3639,
389,
31,
203,
565,
289,
203,
27699,
565,
445,
1001,
18927,
67,
2738,
12,
203,
565,
262,
203,
3639,
2713,
7010,
3639,
12562,
7010,
565,
288,
203,
3639,
2975,
3943,
273,
296,
6054,
13506,
203,
3639,
1001,
5460,
429,
67,
2738,
5621,
203,
565,
289,
203,
377,
203,
377,
203,
565,
445,
10734,
986,
12,
2867,
8526,
3778,
389,
13277,
13,
1071,
5024,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
2216,
273,
389,
20409,
986,
12,
6054,
3943,
16,
389,
13277,
1769,
203,
565,
289,
203,
377,
203,
565,
445,
10734,
3288,
2
] |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol";
contract CryptoStar is ERC721, Ownable {
// https://ethereum.meta.stackexchange.com/questions/443/blog-simple-storage-patterns-in-solidity
// Using struct mapping with internal bool indicating Star is valid
struct Star {
string name;
bool isStar;
}
// Name and symbol of CryptoStar token
string public constant name = "CryptoStar";
string public constant symbol = "CST";
// Mapping of Star tokenIds and Star data
mapping(uint256 => Star) public tokenIdToStarInfo;
// Mapping of Stars for sale (tokenId) and price
mapping(uint256 => uint256) public starsForSale;
// Way to check if the star data exists and is valid
function isStar(uint256 _tokenId) public view returns(bool isIndeed) {
return tokenIdToStarInfo[_tokenId].isStar;
}
// Claim a star
function claimStar(string _name, uint256 _tokenId) public {
require(!isStar(_tokenId), "Star tokenId already exists");
tokenIdToStarInfo[_tokenId].name = _name;
tokenIdToStarInfo[_tokenId].isStar = true;
_mint(msg.sender, _tokenId);
}
// Find a star
function lookUptokenIdToStarInfo(uint256 _tokenId) public view returns (string, address) {
require(isStar(_tokenId), "not a valid Star tokenId");
return (tokenIdToStarInfo[_tokenId].name, ownerOf(_tokenId));
}
// List a star for sale
function putStarUpForSale(uint256 _tokenId, uint256 _price) public {
require(ownerOf(_tokenId) == msg.sender, "only owner is allowed to put a Star up for sale");
starsForSale[_tokenId] = _price;
}
// Buy a star
function buyStar(uint256 _tokenId) public payable {
require(starsForSale[_tokenId] > 0, "Star tokenId is not for sale");
uint256 starCost = starsForSale[_tokenId];
address starOwner = ownerOf(_tokenId);
require(msg.value >= starCost, "not enough Wei to buy Star");
_removeTokenFrom(starOwner, _tokenId);
_addTokenTo(msg.sender, _tokenId);
starOwner.transfer(starCost);
if(msg.value > starCost) {
msg.sender.transfer(msg.value - starCost);
}
starsForSale[_tokenId] = 0;
}
// Exchange Stars between two different accounts
function exchangeStars(uint256 _tokenFrom, uint256 _tokenTo) public payable {
require(isStar(_tokenFrom), "not a valid Star 'from' tokenId");
require(isStar(_tokenTo), "not a valid Star 'to' tokenId");
require(ownerOf(_tokenFrom) == msg.sender, "only an owner can initiate a Star transfer");
address to = ownerOf(_tokenTo);
require(ownerOf(_tokenTo) == to, "Star 'to' address is not owner of tokenId");
require(ownerOf(_tokenFrom) != ownerOf(_tokenTo), "can't exchange Stars with the same owner");
_removeTokenFrom(msg.sender, _tokenFrom);
_addTokenTo(to, _tokenFrom);
_removeTokenFrom(to, _tokenTo);
_addTokenTo(msg.sender, _tokenTo);
}
// Owner transfers ownership of a Star to another account
function transferStar(address to, uint256 _tokenId) public payable returns(address) {
require(isStar(_tokenId), "not a valid Star tokenId");
require(ownerOf(_tokenId) == msg.sender, "only owner is allowed to transfer a Star");
_removeTokenFrom(msg.sender, _tokenId);
_addTokenTo(to, _tokenId);
return (to);
}
// https://ethereum.stackexchange.com/questions/11758/converting-oraclize-result-from-string-to-address?rq=1
// Adapted, by Miguel Mota
//
// Parses a string address and returns an address type
function parseAddress(bytes _address) public pure returns (address) {
uint160 m = 0;
uint160 b = 0;
for (uint8 i = 0; i < 20; i++) {
m *= 256;
b = uint160(_address[i]);
m += (b);
}
return address(m);
}
// Expire or kill the CryptoStar contract
function expire() public onlyOwner {
// destroys the contract and returns tokens to Contract owner
selfdestruct(msg.sender);
}
}
| Way to check if the star data exists and is valid | function isStar(uint256 _tokenId) public view returns(bool isIndeed) {
return tokenIdToStarInfo[_tokenId].isStar;
}
| 12,613,070 | [
1,
21831,
358,
866,
309,
326,
10443,
501,
1704,
471,
353,
923,
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,
353,
18379,
12,
11890,
5034,
389,
2316,
548,
13,
1071,
1476,
1135,
12,
6430,
8048,
323,
329,
13,
288,
203,
3639,
327,
1147,
28803,
18379,
966,
63,
67,
2316,
548,
8009,
291,
18379,
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
] |
./partial_match/56/0xa7C062cec3EbF04FFf15f94F11e917c2aAE57a06/sources/StrategyCafeLP.sol | * @dev Takes out 4.5% as system fees from the rewards. 0.5% -> Call Fee 0.5% -> Treasury fee 0.5% -> Strategist fee 3.0% -> BIFI Holders/ | function chargeFees() internal {
uint256 toWbnb = IERC20(brew).balanceOf(address(this)).mul(45).div(1000);
IUniswapRouterETH(unirouter).swapExactTokensForTokens(toWbnb, 0, brewToWbnbRoute, address(this), now.add(600));
uint256 wbnbBal = IERC20(wbnb).balanceOf(address(this));
uint256 callFee = wbnbBal.mul(CALL_FEE).div(MAX_FEE);
IERC20(wbnb).safeTransfer(msg.sender, callFee);
uint256 treasuryHalf = wbnbBal.mul(TREASURY_FEE).div(MAX_FEE).div(2);
IERC20(wbnb).safeTransfer(treasury, treasuryHalf);
IUniswapRouterETH(unirouter).swapExactTokensForTokens(treasuryHalf, 0, wbnbToBifiRoute, treasury, now.add(600));
uint256 rewardsFee = wbnbBal.mul(REWARDS_FEE).div(MAX_FEE);
IERC20(wbnb).safeTransfer(rewards, rewardsFee);
uint256 strategistFee = wbnbBal.mul(STRATEGIST_FEE).div(MAX_FEE);
IERC20(wbnb).safeTransfer(strategist, strategistFee);
}
| 11,060,579 | [
1,
11524,
596,
1059,
18,
25,
9,
487,
2619,
1656,
281,
628,
326,
283,
6397,
18,
374,
18,
25,
9,
317,
3049,
30174,
374,
18,
25,
9,
317,
399,
266,
345,
22498,
14036,
374,
18,
25,
9,
317,
3978,
1287,
376,
14036,
890,
18,
20,
9,
317,
605,
5794,
670,
4665,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
13765,
2954,
281,
1435,
2713,
288,
203,
3639,
2254,
5034,
358,
59,
70,
6423,
273,
467,
654,
39,
3462,
12,
6073,
91,
2934,
12296,
951,
12,
2867,
12,
2211,
13,
2934,
16411,
12,
7950,
2934,
2892,
12,
18088,
1769,
203,
3639,
467,
984,
291,
91,
438,
8259,
1584,
44,
12,
318,
77,
10717,
2934,
22270,
14332,
5157,
1290,
5157,
12,
869,
59,
70,
6423,
16,
374,
16,
324,
16052,
774,
59,
70,
6423,
3255,
16,
1758,
12,
2211,
3631,
2037,
18,
1289,
12,
28133,
10019,
203,
203,
3639,
2254,
5034,
17298,
6423,
38,
287,
273,
467,
654,
39,
3462,
12,
9464,
6423,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
2254,
5034,
745,
14667,
273,
17298,
6423,
38,
287,
18,
16411,
12,
13730,
67,
8090,
41,
2934,
2892,
12,
6694,
67,
8090,
41,
1769,
203,
3639,
467,
654,
39,
3462,
12,
9464,
6423,
2934,
4626,
5912,
12,
3576,
18,
15330,
16,
745,
14667,
1769,
203,
203,
3639,
2254,
5034,
9787,
345,
22498,
16168,
273,
17298,
6423,
38,
287,
18,
16411,
12,
56,
862,
3033,
1099,
61,
67,
8090,
41,
2934,
2892,
12,
6694,
67,
8090,
41,
2934,
2892,
12,
22,
1769,
203,
3639,
467,
654,
39,
3462,
12,
9464,
6423,
2934,
4626,
5912,
12,
27427,
345,
22498,
16,
9787,
345,
22498,
16168,
1769,
203,
3639,
467,
984,
291,
91,
438,
8259,
1584,
44,
12,
318,
77,
10717,
2934,
22270,
14332,
5157,
1290,
5157,
12,
27427,
345,
22498,
16168,
16,
374,
16,
17298,
6423,
774,
38,
704,
3255,
16,
9787,
2
] |
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IDetailedERC20} from "contracts/common/Imports.sol";
import {SafeERC20} from "contracts/libraries/Imports.sol";
import {
Initializable,
ERC20UpgradeSafe,
ReentrancyGuardUpgradeSafe,
PausableUpgradeSafe,
AccessControlUpgradeSafe,
Address as AddressUpgradeSafe,
SafeMath as SafeMathUpgradeSafe,
SignedSafeMath as SignedSafeMathUpgradeSafe
} from "contracts/proxy/Imports.sol";
import {IAddressRegistryV2} from "contracts/registry/Imports.sol";
import {
AggregatorV3Interface,
IOracleAdapter
} from "contracts/oracle/Imports.sol";
import {MetaPoolToken} from "contracts/mapt/MetaPoolToken.sol";
import {
IReservePool,
IWithdrawFeePool,
ILockingPool,
IPoolToken,
ILiquidityPoolV2
} from "./Imports.sol";
/**
* @notice Collect user deposits so they can be lent to the LP Account
* @notice Depositors share pool liquidity
* @notice Reserves are maintained to process withdrawals
* @notice Reserve tokens cannot be lent to the LP Account
* @notice If a user withdraws too early after their deposit, there's a fee
* @notice Tokens borrowed from the pool are tracked with the `MetaPoolToken`
*/
contract PoolTokenV2 is
ILiquidityPoolV2,
IPoolToken,
IReservePool,
IWithdrawFeePool,
ILockingPool,
Initializable,
AccessControlUpgradeSafe,
ReentrancyGuardUpgradeSafe,
PausableUpgradeSafe,
ERC20UpgradeSafe
{
using AddressUpgradeSafe for address;
using SafeMathUpgradeSafe for uint256;
using SignedSafeMathUpgradeSafe for int256;
using SafeERC20 for IDetailedERC20;
uint256 public constant DEFAULT_APT_TO_UNDERLYER_FACTOR = 1000;
uint256 internal constant _MAX_INT256 = 2**255 - 1;
/* ------------------------------- */
/* impl-specific storage variables */
/* ------------------------------- */
// V1
/** @notice used to protect init functions for upgrades */
address public proxyAdmin;
/** @notice true if depositing is locked */
bool public addLiquidityLock;
/** @notice true if withdrawing is locked */
bool public redeemLock;
/** @notice underlying stablecoin */
IDetailedERC20 public override underlyer;
/** @notice USD price feed for the stablecoin */
// AggregatorV3Interface public priceAgg; <-- removed in V2
// V2
/**
* @notice registry to fetch core platform addresses from
* @dev this slot replaces the last V1 slot for the price agg
*/
IAddressRegistryV2 public addressRegistry;
/** @notice seconds since last deposit during which withdrawal fee is charged */
uint256 public override feePeriod;
/** @notice percentage charged for withdrawal fee */
uint256 public override feePercentage;
/** @notice time of last deposit */
mapping(address => uint256) public lastDepositTime;
/** @notice percentage of pool total value available for immediate withdrawal */
uint256 public override reservePercentage;
/* ------------------------------- */
/** @notice Log when the proxy admin is changed */
event AdminChanged(address);
/** @notice Log when the address registry is changed */
event AddressRegistryChanged(address);
/**
* @dev Throw if called by any account other than the proxy admin.
*/
modifier onlyAdmin() {
require(msg.sender == proxyAdmin, "ADMIN_ONLY");
_;
}
/**
* @dev Since the proxy delegate calls to this "logic" contract, any
* storage set by the logic contract's constructor during deploy is
* disregarded and this function is needed to initialize the proxy
* contract's storage according to this contract's layout.
*
* Since storage is not set yet, there is no simple way to protect
* calling this function with owner modifiers. Thus the OpenZeppelin
* `initializer` modifier protects this function from being called
* repeatedly. It should be called during the deployment so that
* it cannot be called by someone else later.
*
* NOTE: this function is copied from the V1 contract and has already
* been called during V1 deployment. It is included here for clarity.
*/
function initialize(
address adminAddress,
IDetailedERC20 underlyer_,
AggregatorV3Interface priceAgg
) external initializer {
require(adminAddress != address(0), "INVALID_ADMIN");
require(address(underlyer_) != address(0), "INVALID_TOKEN");
require(address(priceAgg) != address(0), "INVALID_AGG");
// initialize ancestor storage
__Context_init_unchained();
// __Ownable_init_unchained(); <-- Comment-out for compiler; replaced by AccessControl
__ReentrancyGuard_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained("APY Pool Token", "APT");
// initialize impl-specific storage
_setAdminAddress(adminAddress);
addLiquidityLock = false;
redeemLock = false;
underlyer = underlyer_;
// setPriceAggregator(priceAgg); <-- deprecated in V2.
}
/**
* @dev Note the `initializer` modifier can only be used once in the
* entire contract, so we can't use it here. Instead, we protect
* this function with `onlyAdmin`, which allows only the `proxyAdmin`
* address to call this function. Since that address is in fact
* set to the actual proxy admin during deployment, this ensures
* this function can only be called as part of a delegate call
* during upgrades, i.e. in ProxyAdmin's `upgradeAndCall`.
*/
function initializeUpgrade(address addressRegistry_) external onlyAdmin {
_setAddressRegistry(addressRegistry_);
// Sadly, the AccessControl init is protected by `initializer` so can't
// be called ever again (see above natspec). Fortunately, the init body
// is empty, so we don't actually need to call it.
// __AccessControl_init_unchained();
_setupRole(DEFAULT_ADMIN_ROLE, addressRegistry.emergencySafeAddress());
_setupRole(ADMIN_ROLE, addressRegistry.adminSafeAddress());
_setupRole(EMERGENCY_ROLE, addressRegistry.emergencySafeAddress());
_setupRole(CONTRACT_ROLE, addressRegistry.mAptAddress());
feePeriod = 1 days;
feePercentage = 5;
reservePercentage = 5;
}
function emergencyLock() external override onlyEmergencyRole {
_pause();
}
function emergencyUnlock() external override onlyEmergencyRole {
_unpause();
}
/**
* @dev If no APT tokens have been minted yet, fallback to a fixed ratio.
*/
function addLiquidity(uint256 depositAmount)
external
override
nonReentrant
whenNotPaused
{
require(!addLiquidityLock, "LOCKED");
require(depositAmount > 0, "AMOUNT_INSUFFICIENT");
require(
underlyer.allowance(msg.sender, address(this)) >= depositAmount,
"ALLOWANCE_INSUFFICIENT"
);
// solhint-disable-next-line not-rely-on-time
lastDepositTime[msg.sender] = block.timestamp;
// calculateMintAmount() is not used because deposit value
// is needed for the event
uint256 depositValue = getValueFromUnderlyerAmount(depositAmount);
uint256 poolTotalValue = getPoolTotalValue();
uint256 mintAmount = _calculateMintAmount(depositValue, poolTotalValue);
_mint(msg.sender, mintAmount);
underlyer.safeTransferFrom(msg.sender, address(this), depositAmount);
emit DepositedAPT(
msg.sender,
underlyer,
depositAmount,
mintAmount,
depositValue,
getPoolTotalValue()
);
}
function emergencyLockAddLiquidity() external override onlyEmergencyRole {
addLiquidityLock = true;
emit AddLiquidityLocked();
}
function emergencyUnlockAddLiquidity() external override onlyEmergencyRole {
addLiquidityLock = false;
emit AddLiquidityUnlocked();
}
/**
* @dev May revert if there is not enough in the pool.
*/
function redeem(uint256 aptAmount)
external
override
nonReentrant
whenNotPaused
{
require(!redeemLock, "LOCKED");
require(aptAmount > 0, "AMOUNT_INSUFFICIENT");
require(aptAmount <= balanceOf(msg.sender), "BALANCE_INSUFFICIENT");
uint256 redeemUnderlyerAmt = getUnderlyerAmountWithFee(aptAmount);
require(
redeemUnderlyerAmt <= underlyer.balanceOf(address(this)),
"RESERVE_INSUFFICIENT"
);
_burn(msg.sender, aptAmount);
underlyer.safeTransfer(msg.sender, redeemUnderlyerAmt);
emit RedeemedAPT(
msg.sender,
underlyer,
redeemUnderlyerAmt,
aptAmount,
getValueFromUnderlyerAmount(redeemUnderlyerAmt),
getPoolTotalValue()
);
}
function emergencyLockRedeem() external override onlyEmergencyRole {
redeemLock = true;
emit RedeemLocked();
}
function emergencyUnlockRedeem() external override onlyEmergencyRole {
redeemLock = false;
emit RedeemUnlocked();
}
/**
* @dev permissioned with CONTRACT_ROLE
*/
function transferToLpAccount(uint256 amount)
external
override
nonReentrant
whenNotPaused
onlyContractRole
{
underlyer.safeTransfer(addressRegistry.lpAccountAddress(), amount);
}
/**
* @notice Set the new proxy admin
* @param adminAddress The new proxy admin
*/
function emergencySetAdminAddress(address adminAddress)
external
onlyEmergencyRole
{
_setAdminAddress(adminAddress);
}
/**
* @notice Set the new address registry
* @param addressRegistry_ The new address registry
*/
function emergencySetAddressRegistry(address addressRegistry_)
external
onlyEmergencyRole
{
_setAddressRegistry(addressRegistry_);
}
function setFeePeriod(uint256 feePeriod_) external override onlyAdminRole {
feePeriod = feePeriod_;
emit FeePeriodChanged(feePeriod_);
}
function setFeePercentage(uint256 feePercentage_)
external
override
onlyAdminRole
{
feePercentage = feePercentage_;
emit FeePercentageChanged(feePercentage_);
}
function setReservePercentage(uint256 reservePercentage_)
external
override
onlyAdminRole
{
reservePercentage = reservePercentage_;
emit ReservePercentageChanged(reservePercentage_);
}
function calculateMintAmount(uint256 depositAmount)
external
view
override
returns (uint256)
{
uint256 depositValue = getValueFromUnderlyerAmount(depositAmount);
uint256 poolTotalValue = getPoolTotalValue();
return _calculateMintAmount(depositValue, poolTotalValue);
}
/**
* @dev To check if fee will be applied, use `isEarlyRedeem`.
*/
function getUnderlyerAmountWithFee(uint256 aptAmount)
public
view
override
returns (uint256)
{
uint256 redeemUnderlyerAmt = getUnderlyerAmount(aptAmount);
if (isEarlyRedeem()) {
uint256 fee = redeemUnderlyerAmt.mul(feePercentage).div(100);
redeemUnderlyerAmt = redeemUnderlyerAmt.sub(fee);
}
return redeemUnderlyerAmt;
}
function getUnderlyerAmount(uint256 aptAmount)
public
view
override
returns (uint256)
{
if (aptAmount == 0) {
return 0;
}
require(totalSupply() > 0, "INSUFFICIENT_TOTAL_SUPPLY");
// the below is mathematically equivalent to:
//
// getUnderlyerAmountFromValue(getAPTValue(aptAmount));
//
// but composing the two functions leads to early loss
// of precision from division, so it's better to do it
// this way:
uint256 underlyerPrice = getUnderlyerPrice();
uint256 decimals = underlyer.decimals();
return
aptAmount
.mul(getPoolTotalValue())
.mul(10**decimals)
.div(totalSupply())
.div(underlyerPrice);
}
/**
* @dev `lastDepositTime` is stored each time user makes a deposit, so
* the waiting period is restarted on each deposit.
*/
function isEarlyRedeem() public view override returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp.sub(lastDepositTime[msg.sender]) < feePeriod;
}
/**
* @dev Total value also includes that have been borrowed from the pool
* @dev Typically it is the LP Account that borrows from the pool
*/
function getPoolTotalValue() public view override returns (uint256) {
uint256 underlyerValue = _getPoolUnderlyerValue();
uint256 mAptValue = _getDeployedValue();
return underlyerValue.add(mAptValue);
}
function getAPTValue(uint256 aptAmount)
external
view
override
returns (uint256)
{
require(totalSupply() > 0, "INSUFFICIENT_TOTAL_SUPPLY");
return aptAmount.mul(getPoolTotalValue()).div(totalSupply());
}
function getValueFromUnderlyerAmount(uint256 underlyerAmount)
public
view
override
returns (uint256)
{
if (underlyerAmount == 0) {
return 0;
}
uint256 decimals = underlyer.decimals();
return getUnderlyerPrice().mul(underlyerAmount).div(10**decimals);
}
function getUnderlyerPrice() public view override returns (uint256) {
IOracleAdapter oracleAdapter =
IOracleAdapter(addressRegistry.oracleAdapterAddress());
return oracleAdapter.getAssetPrice(address(underlyer));
}
/**
* @dev This "top-up" value should satisfy:
*
* top-up USD value + pool underlyer USD value
* = (reserve %) * pool deployed value (after unwinding)
*
* @dev Taking the percentage of the pool's current deployed value
* is not sufficient, because the requirement is to have the
* resulting values after unwinding capital satisfy the
* above equation.
*
* More precisely:
*
* R_pre = pool underlyer USD value before pushing unwound
* capital to the pool
* R_post = pool underlyer USD value after pushing
* DV_pre = pool's deployed USD value before unwinding
* DV_post = pool's deployed USD value after unwinding
* rPerc = the reserve percentage as a whole number
* out of 100
*
* We want:
*
* R_post = (rPerc / 100) * DV_post (equation 1)
*
* where R_post = R_pre + top-up value
* DV_post = DV_pre - top-up value
*
* Making the latter substitutions in equation 1, gives:
*
* top-up value = (rPerc * DV_pre - 100 * R_pre) / (100 + rPerc)
*/
function getReserveTopUpValue() external view override returns (int256) {
uint256 unnormalizedTargetValue =
_getDeployedValue().mul(reservePercentage);
uint256 unnormalizedUnderlyerValue = _getPoolUnderlyerValue().mul(100);
require(unnormalizedTargetValue <= _MAX_INT256, "SIGNED_INT_OVERFLOW");
require(
unnormalizedUnderlyerValue <= _MAX_INT256,
"SIGNED_INT_OVERFLOW"
);
int256 topUpValue =
int256(unnormalizedTargetValue)
.sub(int256(unnormalizedUnderlyerValue))
.div(int256(reservePercentage).add(100));
return topUpValue;
}
function _setAdminAddress(address adminAddress) internal {
require(adminAddress != address(0), "INVALID_ADMIN");
proxyAdmin = adminAddress;
emit AdminChanged(adminAddress);
}
function _setAddressRegistry(address addressRegistry_) internal {
require(addressRegistry_.isContract(), "INVALID_ADDRESS");
addressRegistry = IAddressRegistryV2(addressRegistry_);
emit AddressRegistryChanged(addressRegistry_);
}
/**
* @dev This hook is in-place to block inter-user APT transfers, as it
* is one avenue that can be used by arbitrageurs to drain the
* reserves.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override {
super._beforeTokenTransfer(from, to, amount);
// allow minting and burning
if (from == address(0) || to == address(0)) return;
// block transfer between users
revert("INVALID_TRANSFER");
}
/**
* @dev amount of APT minted should be in same ratio to APT supply
* as deposit value is to pool's total value, i.e.:
*
* mint amount / total supply
* = deposit value / pool total value
*
* For denominators, pre or post-deposit amounts can be used.
* The important thing is they are consistent, i.e. both pre-deposit
* or both post-deposit.
*/
function _calculateMintAmount(uint256 depositValue, uint256 poolTotalValue)
internal
view
returns (uint256)
{
uint256 totalSupply = totalSupply();
if (poolTotalValue == 0 || totalSupply == 0) {
return depositValue.mul(DEFAULT_APT_TO_UNDERLYER_FACTOR);
}
return (depositValue.mul(totalSupply)).div(poolTotalValue);
}
/**
* @notice Get the USD value of tokens in the pool
* @return The USD value
*/
function _getPoolUnderlyerValue() internal view returns (uint256) {
return getValueFromUnderlyerAmount(underlyer.balanceOf(address(this)));
}
/**
* @notice Get the USD value of tokens owed to the pool
* @dev Tokens from the pool are typically borrowed by the LP Account
* @dev Tokens borrowed from the pool are tracked with mAPT
* @return The USD value
*/
function _getDeployedValue() internal view returns (uint256) {
MetaPoolToken mApt = MetaPoolToken(addressRegistry.mAptAddress());
return mApt.getDeployedValue(address(this));
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {IDetailedERC20} from "./IDetailedERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {
ReentrancyGuard
} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {AccessControl} from "./AccessControl.sol";
import {INameIdentifier} from "./INameIdentifier.sol";
import {IAssetAllocation} from "./IAssetAllocation.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {NamedAddressSet} from "./NamedAddressSet.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {
Initializable
} from "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
import {
OwnableUpgradeSafe
} from "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import {
ERC20UpgradeSafe
} from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";
import {
ReentrancyGuardUpgradeSafe
} from "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import {
PausableUpgradeSafe
} from "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol";
import {AccessControlUpgradeSafe} from "./AccessControlUpgradeSafe.sol";
import {ProxyAdmin} from "@openzeppelin/contracts/proxy/ProxyAdmin.sol";
import {
TransparentUpgradeableProxy
} from "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol";
/* Aliases don't persist so we can't rename them here, but you should
* rename them at point of import with the "UpgradeSafe" prefix, e.g.
* import {Address as AddressUpgradeSafe} etc.
*/
import {
Address
} from "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol";
import {
SafeMath
} from "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import {
SignedSafeMath
} from "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IAddressRegistryV2} from "./IAddressRegistryV2.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {AggregatorV3Interface, FluxAggregator} from "./FluxAggregator.sol";
import {IOracleAdapter} from "./IOracleAdapter.sol";
import {IOverrideOracle} from "./IOverrideOracle.sol";
import {ILockingOracle} from "./ILockingOracle.sol";
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IDetailedERC20} from "contracts/common/Imports.sol";
import {SafeERC20} from "contracts/libraries/Imports.sol";
import {
Initializable,
ERC20UpgradeSafe,
ReentrancyGuardUpgradeSafe,
PausableUpgradeSafe,
AccessControlUpgradeSafe,
Address as AddressUpgradeSafe,
SafeMath as SafeMathUpgradeSafe,
SignedSafeMath as SignedSafeMathUpgradeSafe
} from "contracts/proxy/Imports.sol";
import {ILpAccount} from "contracts/lpaccount/Imports.sol";
import {IAddressRegistryV2} from "contracts/registry/Imports.sol";
import {ILockingOracle} from "contracts/oracle/Imports.sol";
import {IReservePool} from "contracts/pool/Imports.sol";
import {
IErc20Allocation,
IAssetAllocationRegistry,
Erc20AllocationConstants
} from "contracts/tvl/Imports.sol";
import {ILpAccountFunder} from "./ILpAccountFunder.sol";
/**
* @notice This contract has hybrid functionality:
*
* - It acts as a token that tracks the capital that has been pulled
* ("deployed") from APY Finance pools (PoolToken contracts)
*
* - It is permissioned to transfer funds between the pools and the
* LP Account contract.
*
* @dev When MetaPoolToken pulls capital from the pools to the LP Account, it
* will mint mAPT for each pool. Conversely, when MetaPoolToken withdraws funds
* from the LP Account to the pools, it will burn mAPT for each pool.
*
* The ratio of each pool's mAPT balance to the total mAPT supply determines
* the amount of the TVL dedicated to the pool.
*
*
* DEPLOY CAPITAL TO YIELD FARMING STRATEGIES
* Mints appropriate mAPT amount to track share of deployed TVL owned by a pool.
*
* +-------------+ MetaPoolToken.fundLpAccount +-----------+
* | |------------------------------>| |
* | PoolTokenV2 | MetaPoolToken.mint | LpAccount |
* | |<------------------------------| |
* +-------------+ +-----------+
*
*
* WITHDRAW CAPITAL FROM YIELD FARMING STRATEGIES
* Uses mAPT to calculate the amount of capital returned to the PoolToken.
*
* +-------------+ MetaPoolToken.withdrawFromLpAccount +-----------+
* | |<--------------------------------------| |
* | PoolTokenV2 | MetaPoolToken.burn | LpAccount |
* | |-------------------------------------->| |
* +-------------+ +-----------+
*/
contract MetaPoolToken is
Initializable,
AccessControlUpgradeSafe,
ReentrancyGuardUpgradeSafe,
PausableUpgradeSafe,
ERC20UpgradeSafe,
ILpAccountFunder,
Erc20AllocationConstants
{
using AddressUpgradeSafe for address;
using SafeMathUpgradeSafe for uint256;
using SignedSafeMathUpgradeSafe for int256;
using SafeERC20 for IDetailedERC20;
uint256 public constant DEFAULT_MAPT_TO_UNDERLYER_FACTOR = 1000;
/* ------------------------------- */
/* impl-specific storage variables */
/* ------------------------------- */
/** @notice used to protect init functions for upgrades */
address public proxyAdmin;
/** @notice used to protect mint and burn function */
IAddressRegistryV2 public addressRegistry;
/* ------------------------------- */
event Mint(address acccount, uint256 amount);
event Burn(address acccount, uint256 amount);
event AdminChanged(address);
event AddressRegistryChanged(address);
/**
* @dev Throws if called by any account other than the proxy admin.
*/
modifier onlyAdmin() {
require(msg.sender == proxyAdmin, "ADMIN_ONLY");
_;
}
/**
* @dev Since the proxy delegate calls to this "logic" contract, any
* storage set by the logic contract's constructor during deploy is
* disregarded and this function is needed to initialize the proxy
* contract's storage according to this contract's layout.
*
* Since storage is not set yet, there is no simple way to protect
* calling this function with owner modifiers. Thus the OpenZeppelin
* `initializer` modifier protects this function from being called
* repeatedly. It should be called during the deployment so that
* it cannot be called by someone else later.
*/
function initialize(address adminAddress, address addressRegistry_)
external
initializer
{
require(adminAddress != address(0), "INVALID_ADMIN");
// initialize ancestor storage
__Context_init_unchained();
__AccessControl_init_unchained();
__ReentrancyGuard_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained("APY MetaPool Token", "mAPT");
// initialize impl-specific storage
_setAdminAddress(adminAddress);
_setAddressRegistry(addressRegistry_);
_setupRole(DEFAULT_ADMIN_ROLE, addressRegistry.emergencySafeAddress());
_setupRole(LP_ROLE, addressRegistry.lpSafeAddress());
_setupRole(EMERGENCY_ROLE, addressRegistry.emergencySafeAddress());
}
/**
* @dev Dummy function to show how one would implement an init function
* for future upgrades. Note the `initializer` modifier can only be used
* once in the entire contract, so we can't use it here. Instead,
* we set the proxy admin address as a variable and protect this
* function with `onlyAdmin`, which only allows the proxy admin
* to call this function during upgrades.
*/
// solhint-disable-next-line no-empty-blocks
function initializeUpgrade() external virtual onlyAdmin {}
/**
* @notice Set the new proxy admin
* @param adminAddress The new proxy admin
*/
function emergencySetAdminAddress(address adminAddress)
external
onlyEmergencyRole
{
_setAdminAddress(adminAddress);
}
/**
* @notice Sets the address registry
* @param addressRegistry_ the address of the registry
*/
function emergencySetAddressRegistry(address addressRegistry_)
external
onlyEmergencyRole
{
_setAddressRegistry(addressRegistry_);
}
function fundLpAccount(bytes32[] calldata poolIds)
external
override
nonReentrant
onlyLpRole
{
(IReservePool[] memory pools, int256[] memory amounts) =
getRebalanceAmounts(poolIds);
uint256[] memory fundAmounts = _getFundAmounts(amounts);
_fundLpAccount(pools, fundAmounts);
emit FundLpAccount(poolIds, fundAmounts);
}
function emergencyFundLpAccount(
IReservePool[] calldata pools,
uint256[] calldata amounts
) external override nonReentrant onlyEmergencyRole {
_fundLpAccount(pools, amounts);
emit EmergencyFundLpAccount(pools, amounts);
}
function withdrawFromLpAccount(bytes32[] calldata poolIds)
external
override
nonReentrant
onlyLpRole
{
(IReservePool[] memory pools, int256[] memory amounts) =
getRebalanceAmounts(poolIds);
uint256[] memory withdrawAmounts = _getWithdrawAmounts(amounts);
_withdrawFromLpAccount(pools, withdrawAmounts);
emit WithdrawFromLpAccount(poolIds, withdrawAmounts);
}
function emergencyWithdrawFromLpAccount(
IReservePool[] calldata pools,
uint256[] calldata amounts
) external override nonReentrant onlyEmergencyRole {
_withdrawFromLpAccount(pools, amounts);
emit EmergencyWithdrawFromLpAccount(pools, amounts);
}
/**
* @notice Get the USD-denominated value (in wei) of the pool's share
* of the deployed capital, as tracked by the mAPT token.
* @return The value deployed to the LP Account
*/
function getDeployedValue(address pool) external view returns (uint256) {
uint256 balance = balanceOf(pool);
uint256 totalSupply = totalSupply();
if (totalSupply == 0 || balance == 0) return 0;
return _getTvl().mul(balance).div(totalSupply);
}
/**
* @notice Returns the (signed) top-up amount for each pool ID given.
* A positive (negative) sign means the reserve level is in deficit
* (excess) of required percentage.
* @param poolIds array of pool identifiers
* @return The array of pools
* @return An array of rebalance amounts
*/
function getRebalanceAmounts(bytes32[] memory poolIds)
public
view
returns (IReservePool[] memory, int256[] memory)
{
IReservePool[] memory pools = new IReservePool[](poolIds.length);
int256[] memory rebalanceAmounts = new int256[](poolIds.length);
for (uint256 i = 0; i < poolIds.length; i++) {
IReservePool pool =
IReservePool(addressRegistry.getAddress(poolIds[i]));
int256 rebalanceAmount = pool.getReserveTopUpValue();
pools[i] = pool;
rebalanceAmounts[i] = rebalanceAmount;
}
return (pools, rebalanceAmounts);
}
function _setAdminAddress(address adminAddress) internal {
require(adminAddress != address(0), "INVALID_ADMIN");
proxyAdmin = adminAddress;
emit AdminChanged(adminAddress);
}
function _setAddressRegistry(address addressRegistry_) internal {
require(addressRegistry_.isContract(), "INVALID_ADDRESS");
addressRegistry = IAddressRegistryV2(addressRegistry_);
emit AddressRegistryChanged(addressRegistry_);
}
function _fundLpAccount(
IReservePool[] memory pools,
uint256[] memory amounts
) internal {
address lpAccountAddress = addressRegistry.lpAccountAddress();
require(lpAccountAddress != address(0), "INVALID_LP_ACCOUNT"); // defensive check -- should never happen
_multipleMintAndTransfer(pools, amounts);
_registerPoolUnderlyers(pools);
}
function _multipleMintAndTransfer(
IReservePool[] memory pools,
uint256[] memory amounts
) internal {
uint256[] memory deltas = _calculateDeltas(pools, amounts);
// MUST do the actual minting after calculating *all* mint amounts,
// otherwise due to Chainlink not updating during a transaction,
// the totalSupply will change while TVL doesn't.
//
// Using the pre-mint TVL and totalSupply gives the same answer
// as using post-mint values.
for (uint256 i = 0; i < pools.length; i++) {
IReservePool pool = pools[i];
uint256 mintAmount = deltas[i];
uint256 transferAmount = amounts[i];
_mintAndTransfer(pool, mintAmount, transferAmount);
}
ILockingOracle oracleAdapter = _getOracleAdapter();
oracleAdapter.lock();
}
function _mintAndTransfer(
IReservePool pool,
uint256 mintAmount,
uint256 transferAmount
) internal {
if (mintAmount == 0) {
return;
}
_mint(address(pool), mintAmount);
pool.transferToLpAccount(transferAmount);
emit Mint(address(pool), mintAmount);
}
function _withdrawFromLpAccount(
IReservePool[] memory pools,
uint256[] memory amounts
) internal {
address lpAccountAddress = addressRegistry.lpAccountAddress();
require(lpAccountAddress != address(0), "INVALID_LP_ACCOUNT"); // defensive check -- should never happen
_multipleBurnAndTransfer(pools, amounts);
_registerPoolUnderlyers(pools);
}
function _multipleBurnAndTransfer(
IReservePool[] memory pools,
uint256[] memory amounts
) internal {
address lpAccount = addressRegistry.lpAccountAddress();
require(lpAccount != address(0), "INVALID_LP_ACCOUNT"); // defensive check -- should never happen
uint256[] memory deltas = _calculateDeltas(pools, amounts);
// MUST do the actual burning after calculating *all* burn amounts,
// otherwise due to Chainlink not updating during a transaction,
// the totalSupply will change while TVL doesn't.
//
// Using the pre-burn TVL and totalSupply gives the same answer
// as using post-burn values.
for (uint256 i = 0; i < pools.length; i++) {
IReservePool pool = pools[i];
uint256 burnAmount = deltas[i];
uint256 transferAmount = amounts[i];
_burnAndTransfer(pool, lpAccount, burnAmount, transferAmount);
}
ILockingOracle oracleAdapter = _getOracleAdapter();
oracleAdapter.lock();
}
function _burnAndTransfer(
IReservePool pool,
address lpAccount,
uint256 burnAmount,
uint256 transferAmount
) internal {
if (burnAmount == 0) {
return;
}
_burn(address(pool), burnAmount);
ILpAccount(lpAccount).transferToPool(address(pool), transferAmount);
emit Burn(address(pool), burnAmount);
}
/**
* @notice Register an asset allocation for the account with each pool underlyer
* @param pools list of pool amounts whose pool underlyers will be registered
*/
function _registerPoolUnderlyers(IReservePool[] memory pools) internal {
IAssetAllocationRegistry tvlManager =
IAssetAllocationRegistry(addressRegistry.getAddress("tvlManager"));
IErc20Allocation erc20Allocation =
IErc20Allocation(
address(
tvlManager.getAssetAllocation(Erc20AllocationConstants.NAME)
)
);
for (uint256 i = 0; i < pools.length; i++) {
IDetailedERC20 underlyer =
IDetailedERC20(address(pools[i].underlyer()));
if (!erc20Allocation.isErc20TokenRegistered(underlyer)) {
erc20Allocation.registerErc20Token(underlyer);
}
}
}
/**
* @notice Get the USD value of all assets in the system, not just those
* being managed by the AccountManager but also the pool underlyers.
*
* Note this is NOT the same as the total value represented by the
* total mAPT supply, i.e. the "deployed capital".
*
* @dev Chainlink nodes read from the TVLManager, pull the
* prices from market feeds, and submits the calculated total value
* to an aggregator contract.
*
* USD prices have 8 decimals.
*
* @return "Total Value Locked", the USD value of all APY Finance assets.
*/
function _getTvl() internal view returns (uint256) {
ILockingOracle oracleAdapter = _getOracleAdapter();
return oracleAdapter.getTvl();
}
function _getOracleAdapter() internal view returns (ILockingOracle) {
address oracleAdapterAddress = addressRegistry.oracleAdapterAddress();
return ILockingOracle(oracleAdapterAddress);
}
function _calculateDeltas(
IReservePool[] memory pools,
uint256[] memory amounts
) internal view returns (uint256[] memory) {
require(pools.length == amounts.length, "LENGTHS_MUST_MATCH");
uint256[] memory deltas = new uint256[](pools.length);
for (uint256 i = 0; i < pools.length; i++) {
IReservePool pool = pools[i];
uint256 amount = amounts[i];
IDetailedERC20 underlyer = pool.underlyer();
uint256 tokenPrice = pool.getUnderlyerPrice();
uint8 decimals = underlyer.decimals();
deltas[i] = _calculateDelta(amount, tokenPrice, decimals);
}
return deltas;
}
/**
* @notice Calculate mAPT amount for given pool's underlyer amount.
* @param amount Pool underlyer amount to be converted
* @param tokenPrice Pool underlyer's USD price (in wei) per underlyer token
* @param decimals Pool underlyer's number of decimals
* @dev Price parameter is in units of wei per token ("big" unit), since
* attempting to express wei per token bit ("small" unit) will be
* fractional, requiring fixed-point representation. This means we need
* to also pass in the underlyer's number of decimals to do the appropriate
* multiplication in the calculation.
* @dev amount of APT minted should be in same ratio to APT supply
* as deposit value is to pool's total value, i.e.:
*
* mint amount / total supply
* = deposit value / pool total value
*
* For denominators, pre or post-deposit amounts can be used.
* The important thing is they are consistent, i.e. both pre-deposit
* or both post-deposit.
*/
function _calculateDelta(
uint256 amount,
uint256 tokenPrice,
uint8 decimals
) internal view returns (uint256) {
uint256 value = amount.mul(tokenPrice).div(10**uint256(decimals));
uint256 totalValue = _getTvl();
uint256 totalSupply = totalSupply();
if (totalValue == 0 || totalSupply == 0) {
return value.mul(DEFAULT_MAPT_TO_UNDERLYER_FACTOR);
}
return value.mul(totalSupply).div(totalValue);
}
function _getFundAmounts(int256[] memory amounts)
internal
pure
returns (uint256[] memory)
{
uint256[] memory fundAmounts = new uint256[](amounts.length);
for (uint256 i = 0; i < amounts.length; i++) {
int256 amount = amounts[i];
fundAmounts[i] = amount < 0 ? uint256(-amount) : 0;
}
return fundAmounts;
}
function _getWithdrawAmounts(int256[] memory amounts)
internal
pure
returns (uint256[] memory)
{
uint256[] memory withdrawAmounts = new uint256[](amounts.length);
for (uint256 i = 0; i < amounts.length; i++) {
int256 amount = amounts[i];
withdrawAmounts[i] = amount > 0 ? uint256(amount) : 0;
}
return withdrawAmounts;
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IReservePool} from "./IReservePool.sol";
import {IWithdrawFeePool} from "./IWithdrawFeePool.sol";
import {ILockingPool} from "./ILockingPool.sol";
import {IPoolToken} from "./IPoolToken.sol";
import {ILiquidityPoolV2} from "./ILiquidityPoolV2.sol";
// 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: BUSDL-1.1
pragma solidity 0.6.11;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IDetailedERC20 is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 () internal {
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.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: BUSL-1.1
pragma solidity 0.6.11;
import {
AccessControl as OZAccessControl
} from "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @notice Extends OpenZeppelin AccessControl contract with modifiers
* @dev This contract and AccessControlUpgradeSafe are essentially duplicates.
*/
contract AccessControl is OZAccessControl {
/** @notice access control roles **/
bytes32 public constant CONTRACT_ROLE = keccak256("CONTRACT_ROLE");
bytes32 public constant LP_ROLE = keccak256("LP_ROLE");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE");
modifier onlyLpRole() {
require(hasRole(LP_ROLE, _msgSender()), "NOT_LP_ROLE");
_;
}
modifier onlyContractRole() {
require(hasRole(CONTRACT_ROLE, _msgSender()), "NOT_CONTRACT_ROLE");
_;
}
modifier onlyAdminRole() {
require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE");
_;
}
modifier onlyEmergencyRole() {
require(hasRole(EMERGENCY_ROLE, _msgSender()), "NOT_EMERGENCY_ROLE");
_;
}
modifier onlyLpOrContractRole() {
require(
hasRole(LP_ROLE, _msgSender()) ||
hasRole(CONTRACT_ROLE, _msgSender()),
"NOT_LP_OR_CONTRACT_ROLE"
);
_;
}
modifier onlyAdminOrContractRole() {
require(
hasRole(ADMIN_ROLE, _msgSender()) ||
hasRole(CONTRACT_ROLE, _msgSender()),
"NOT_ADMIN_OR_CONTRACT_ROLE"
);
_;
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice Used by the `NamedAddressSet` library to store sets of contracts
*/
interface INameIdentifier {
/// @notice Should be implemented as a constant value
// solhint-disable-next-line func-name-mixedcase
function NAME() external view returns (string memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {INameIdentifier} from "./INameIdentifier.sol";
/**
* @notice For use with the `TvlManager` to track the value locked in a protocol
*/
interface IAssetAllocation is INameIdentifier {
struct TokenData {
address token;
string symbol;
uint8 decimals;
}
/**
* @notice Get data for the underlying tokens stored in the protocol
* @return The array of `TokenData`
*/
function tokens() external view returns (TokenData[] memory);
/**
* @notice Get the number of different tokens stored in the protocol
* @return The number of tokens
*/
function numberOfTokens() external view returns (uint256);
/**
* @notice Get an account's balance for a token stored in the protocol
* @dev The token index should be ordered the same as the `tokens()` array
* @param account The account to get the balance for
* @param tokenIndex The index of the token to get the balance for
* @return The account's balance
*/
function balanceOf(address account, uint8 tokenIndex)
external
view
returns (uint256);
/**
* @notice Get the symbol of a token stored in the protocol
* @dev The token index should be ordered the same as the `tokens()` array
* @param tokenIndex The index of the token
* @return The symbol of the token
*/
function symbolOf(uint8 tokenIndex) external view returns (string memory);
/**
* @notice Get the decimals of a token stored in the protocol
* @dev The token index should be ordered the same as the `tokens()` array
* @param tokenIndex The index of the token
* @return The decimals of the token
*/
function decimalsOf(uint8 tokenIndex) external view returns (uint8);
}
// 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.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: 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.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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 {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @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 {_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) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_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 {
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 {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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;
// 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];
}
// 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);
}
// 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))));
}
// 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));
}
}
// 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: BUSDL-1.1
pragma solidity 0.6.11;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {IAssetAllocation, INameIdentifier} from "contracts/common/Imports.sol";
import {IZap, ISwap} from "contracts/lpaccount/Imports.sol";
/**
* @notice Stores a set of addresses that can be looked up by name
* @notice Addresses can be added or removed dynamically
* @notice Useful for keeping track of unique deployed contracts
* @dev Each address must be a contract with a `NAME` constant for lookup
*/
library NamedAddressSet {
using EnumerableSet for EnumerableSet.AddressSet;
struct Set {
EnumerableSet.AddressSet _namedAddresses;
mapping(string => INameIdentifier) _nameLookup;
}
struct AssetAllocationSet {
Set _inner;
}
struct ZapSet {
Set _inner;
}
struct SwapSet {
Set _inner;
}
function _add(Set storage set, INameIdentifier namedAddress) private {
require(Address.isContract(address(namedAddress)), "INVALID_ADDRESS");
require(
!set._namedAddresses.contains(address(namedAddress)),
"DUPLICATE_ADDRESS"
);
string memory name = namedAddress.NAME();
require(bytes(name).length != 0, "INVALID_NAME");
require(address(set._nameLookup[name]) == address(0), "DUPLICATE_NAME");
set._namedAddresses.add(address(namedAddress));
set._nameLookup[name] = namedAddress;
}
function _remove(Set storage set, string memory name) private {
address namedAddress = address(set._nameLookup[name]);
require(namedAddress != address(0), "INVALID_NAME");
set._namedAddresses.remove(namedAddress);
delete set._nameLookup[name];
}
function _contains(Set storage set, INameIdentifier namedAddress)
private
view
returns (bool)
{
return set._namedAddresses.contains(address(namedAddress));
}
function _length(Set storage set) private view returns (uint256) {
return set._namedAddresses.length();
}
function _at(Set storage set, uint256 index)
private
view
returns (INameIdentifier)
{
return INameIdentifier(set._namedAddresses.at(index));
}
function _get(Set storage set, string memory name)
private
view
returns (INameIdentifier)
{
return set._nameLookup[name];
}
function _names(Set storage set) private view returns (string[] memory) {
uint256 length_ = set._namedAddresses.length();
string[] memory names_ = new string[](length_);
for (uint256 i = 0; i < length_; i++) {
INameIdentifier namedAddress =
INameIdentifier(set._namedAddresses.at(i));
names_[i] = namedAddress.NAME();
}
return names_;
}
function add(
AssetAllocationSet storage set,
IAssetAllocation assetAllocation
) internal {
_add(set._inner, assetAllocation);
}
function remove(AssetAllocationSet storage set, string memory name)
internal
{
_remove(set._inner, name);
}
function contains(
AssetAllocationSet storage set,
IAssetAllocation assetAllocation
) internal view returns (bool) {
return _contains(set._inner, assetAllocation);
}
function length(AssetAllocationSet storage set)
internal
view
returns (uint256)
{
return _length(set._inner);
}
function at(AssetAllocationSet storage set, uint256 index)
internal
view
returns (IAssetAllocation)
{
return IAssetAllocation(address(_at(set._inner, index)));
}
function get(AssetAllocationSet storage set, string memory name)
internal
view
returns (IAssetAllocation)
{
return IAssetAllocation(address(_get(set._inner, name)));
}
function names(AssetAllocationSet storage set)
internal
view
returns (string[] memory)
{
return _names(set._inner);
}
function add(ZapSet storage set, IZap zap) internal {
_add(set._inner, zap);
}
function remove(ZapSet storage set, string memory name) internal {
_remove(set._inner, name);
}
function contains(ZapSet storage set, IZap zap)
internal
view
returns (bool)
{
return _contains(set._inner, zap);
}
function length(ZapSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(ZapSet storage set, uint256 index)
internal
view
returns (IZap)
{
return IZap(address(_at(set._inner, index)));
}
function get(ZapSet storage set, string memory name)
internal
view
returns (IZap)
{
return IZap(address(_get(set._inner, name)));
}
function names(ZapSet storage set) internal view returns (string[] memory) {
return _names(set._inner);
}
function add(SwapSet storage set, ISwap swap) internal {
_add(set._inner, swap);
}
function remove(SwapSet storage set, string memory name) internal {
_remove(set._inner, name);
}
function contains(SwapSet storage set, ISwap swap)
internal
view
returns (bool)
{
return _contains(set._inner, swap);
}
function length(SwapSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(SwapSet storage set, uint256 index)
internal
view
returns (ISwap)
{
return ISwap(address(_at(set._inner, index)));
}
function get(SwapSet storage set, string memory name)
internal
view
returns (ISwap)
{
return ISwap(address(_get(set._inner, name)));
}
function names(SwapSet storage set)
internal
view
returns (string[] memory)
{
return _names(set._inner);
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IZap} from "./IZap.sol";
import {ISwap} from "./ISwap.sol";
import {ILpAccount} from "./ILpAccount.sol";
import {IZapRegistry} from "./IZapRegistry.sol";
import {ISwapRegistry} from "./ISwapRegistry.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {
IAssetAllocation,
INameIdentifier,
IERC20
} from "contracts/common/Imports.sol";
/**
* @notice Used to define how an LP Account farms an external protocol
*/
interface IZap is INameIdentifier {
/**
* @notice Deploy liquidity to a protocol (i.e. enter a farm)
* @dev Implementation should add liquidity and stake LP tokens
* @param amounts Amount of each token to deploy
*/
function deployLiquidity(uint256[] calldata amounts) external;
/**
* @notice Unwind liquidity from a protocol (i.e exit a farm)
* @dev Implementation should unstake LP tokens and remove liquidity
* @dev If there is only one token to unwind, `index` should be 0
* @param amount Amount of liquidity to unwind
* @param index Which token should be unwound
*/
function unwindLiquidity(uint256 amount, uint8 index) external;
/**
* @notice Claim accrued rewards from the protocol (i.e. harvest yield)
*/
function claim() external;
/**
* @notice Order of tokens for deploy `amounts` and unwind `index`
* @dev Implementation should use human readable symbols
* @dev Order should be the same for deploy and unwind
* @return The array of symbols in order
*/
function sortedSymbols() external view returns (string[] memory);
/**
* @notice Asset allocations to include in TVL
* @dev Requires all allocations that track value deployed to the protocol
* @return An array of the asset allocation names
*/
function assetAllocations() external view returns (string[] memory);
/**
* @notice ERC20 asset allocations to include in TVL
* @dev Should return addresses for all tokens that get deployed or unwound
* @return The array of ERC20 token addresses
*/
function erc20Allocations() external view returns (IERC20[] memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {
IAssetAllocation,
INameIdentifier,
IERC20
} from "contracts/common/Imports.sol";
/**
* @notice Used to define a token swap that can be performed by an LP Account
*/
interface ISwap is INameIdentifier {
/**
* @dev Implementation should perform a token swap
* @param amount The amount of the input token to swap
* @param minAmount The minimum amount of the output token to accept
*/
function swap(uint256 amount, uint256 minAmount) external;
/**
* @notice ERC20 asset allocations to include in TVL
* @dev Should return addresses for all tokens going in and out of the swap
* @return The array of ERC20 token addresses
*/
function erc20Allocations() external view returns (IERC20[] memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice For contracts that provide liquidity to external protocols
*/
interface ILpAccount {
/**
* @notice Deploy liquidity with a registered `IZap`
* @dev The order of token amounts should match `IZap.sortedSymbols`
* @param name The name of the `IZap`
* @param amounts The token amounts to deploy
*/
function deployStrategy(string calldata name, uint256[] calldata amounts)
external;
/**
* @notice Unwind liquidity with a registered `IZap`
* @dev The index should match the order of `IZap.sortedSymbols`
* @param name The name of the `IZap`
* @param amount The amount of the token to unwind
* @param index The index of the token to unwind
*/
function unwindStrategy(
string calldata name,
uint256 amount,
uint8 index
) external;
/**
* @notice Return liquidity to a pool
* @notice Typically used to refill a liquidity pool's reserve
* @dev This should only be callable by the `MetaPoolToken`
* @param pool The `IReservePool` to transfer to
* @param amount The amount of the pool's underlyer token to transer
*/
function transferToPool(address pool, uint256 amount) external;
/**
* @notice Swap tokens with a registered `ISwap`
* @notice Used to compound reward tokens
* @notice Used to rebalance underlyer tokens
* @param name The name of the `IZap`
* @param amount The amount of tokens to swap
* @param minAmount The minimum amount of tokens to receive from the swap
*/
function swap(
string calldata name,
uint256 amount,
uint256 minAmount
) external;
/**
* @notice Claim reward tokens with a registered `IZap`
* @param name The name of the `IZap`
*/
function claim(string calldata name) external;
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IZap} from "./IZap.sol";
/**
* @notice For managing a collection of `IZap` contracts
*/
interface IZapRegistry {
/** @notice Log when a new `IZap` is registered */
event ZapRegistered(IZap zap);
/** @notice Log when an `IZap` is removed */
event ZapRemoved(string name);
/**
* @notice Add a new `IZap` to the registry
* @dev Should not allow duplicate swaps
* @param zap The new `IZap`
*/
function registerZap(IZap zap) external;
/**
* @notice Remove an `IZap` from the registry
* @param name The name of the `IZap` (see `INameIdentifier`)
*/
function removeZap(string calldata name) external;
/**
* @notice Get the names of all registered `IZap`
* @return An array of `IZap` names
*/
function zapNames() external view returns (string[] memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {ISwap} from "./ISwap.sol";
/**
* @notice For managing a collection of `ISwap` contracts
*/
interface ISwapRegistry {
/** @notice Log when a new `ISwap` is registered */
event SwapRegistered(ISwap swap);
/** @notice Log when an `ISwap` is removed */
event SwapRemoved(string name);
/**
* @notice Add a new `ISwap` to the registry
* @dev Should not allow duplicate swaps
* @param swap The new `ISwap`
*/
function registerSwap(ISwap swap) external;
/**
* @notice Remove an `ISwap` from the registry
* @param name The name of the `ISwap` (see `INameIdentifier`)
*/
function removeSwap(string calldata name) external;
/**
* @notice Get the names of all registered `ISwap`
* @return An array of `ISwap` names
*/
function swapNames() external view returns (string[] memory);
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
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 use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been 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;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../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.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
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;
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../Initializable.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 {ERC20MinterPauser}.
*
* 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, 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.
*/
function __ERC20_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {
_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 { }
uint256[44] private __gap;
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/**
* @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].
*/
contract ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// Storing an initial 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 percetange 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.
_notEntered = true;
}
/**
* @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(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../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.
*/
contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe {
/**
* @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 returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.6.11;
import {
AccessControlUpgradeSafe as OZAccessControl
} from "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
/**
* @notice Extends OpenZeppelin upgradeable AccessControl contract with modifiers
* @dev This contract and AccessControl are essentially duplicates.
*/
contract AccessControlUpgradeSafe is OZAccessControl {
/** @notice access control roles **/
bytes32 public constant CONTRACT_ROLE = keccak256("CONTRACT_ROLE");
bytes32 public constant LP_ROLE = keccak256("LP_ROLE");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE");
modifier onlyLpRole() {
require(hasRole(LP_ROLE, _msgSender()), "NOT_LP_ROLE");
_;
}
modifier onlyContractRole() {
require(hasRole(CONTRACT_ROLE, _msgSender()), "NOT_CONTRACT_ROLE");
_;
}
modifier onlyAdminRole() {
require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE");
_;
}
modifier onlyEmergencyRole() {
require(hasRole(EMERGENCY_ROLE, _msgSender()), "NOT_EMERGENCY_ROLE");
_;
}
modifier onlyLpOrContractRole() {
require(
hasRole(LP_ROLE, _msgSender()) ||
hasRole(CONTRACT_ROLE, _msgSender()),
"NOT_LP_OR_CONTRACT_ROLE"
);
_;
}
modifier onlyAdminOrContractRole() {
require(
hasRole(ADMIN_ROLE, _msgSender()) ||
hasRole(CONTRACT_ROLE, _msgSender()),
"NOT_ADMIN_OR_CONTRACT_ROLE"
);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../access/Ownable.sol";
import "./TransparentUpgradeableProxy.sol";
/**
* @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
* explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
*/
contract ProxyAdmin is Ownable {
/**
* @dev Returns the current implementation of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Returns the current admin of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @dev Changes the admin of `proxy` to `newAdmin`.
*
* Requirements:
*
* - This contract must be the current admin of `proxy`.
*/
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
proxy.changeAdmin(newAdmin);
}
/**
* @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
proxy.upgradeTo(implementation);
}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
* {TransparentUpgradeableProxy-upgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/
function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner {
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./UpgradeableProxy.sol";
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is UpgradeableProxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}.
*/
constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(admin_);
}
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external ifAdmin returns (address admin_) {
admin_ = _admin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external virtual ifAdmin {
require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external virtual ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin {
_upgradeTo(newImplementation);
Address.functionDelegateCall(newImplementation, data);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view virtual returns (address adm) {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
adm := sload(slot)
}
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
bytes32 slot = _ADMIN_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal virtual override {
require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
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");
}
}
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) {
// 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;
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on 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 Integer division of two signed integers truncating the quotient, reverts on division by 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 Subtracts two signed integers, reverts on 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 Adds two signed integers, reverts on 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;
}
}
pragma solidity ^0.6.0;
import "../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.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
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;
}
pragma solidity ^0.6.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);
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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, _msgSender()));
* ...
* }
* ```
*
* 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}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_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) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_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 {
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.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Proxy.sol";
import "../utils/Address.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*
* Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
* {TransparentUpgradeableProxy}.
*/
contract UpgradeableProxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
Address.functionDelegateCall(_logic, _data);
}
}
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal virtual {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
bytes32 slot = _IMPLEMENTATION_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, newImplementation)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice The address registry has two important purposes, one which
* is fairly concrete and another abstract.
*
* 1. The registry enables components of the APY.Finance system
* and external systems to retrieve core addresses reliably
* even when the functionality may move to a different
* address.
*
* 2. The registry also makes explicit which contracts serve
* as primary entrypoints for interacting with different
* components. Not every contract is registered here, only
* the ones properly deserving of an identifier. This helps
* define explicit boundaries between groups of contracts,
* each of which is logically cohesive.
*/
interface IAddressRegistryV2 {
/**
* @notice Log when a new address is registered
* @param id The ID of the new address
* @param _address The new address
*/
event AddressRegistered(bytes32 id, address _address);
/**
* @notice Log when an address is removed from the registry
* @param id The ID of the address
* @param _address The address
*/
event AddressDeleted(bytes32 id, address _address);
/**
* @notice Register address with identifier
* @dev Using an existing ID will replace the old address with new
* @dev Currently there is no way to remove an ID, as attempting to
* register the zero address will revert.
*/
function registerAddress(bytes32 id, address address_) external;
/**
* @notice Registers multiple address at once
* @dev Convenient method to register multiple addresses at once.
* @param ids Ids to register addresses under
* @param addresses Addresses to register
*/
function registerMultipleAddresses(
bytes32[] calldata ids,
address[] calldata addresses
) external;
/**
* @notice Removes a registered id and it's associated address
* @dev Delete the address corresponding to the identifier Time-complexity is O(n) where n is the length of `_idList`.
* @param id ID to remove along with it's associated address
*/
function deleteAddress(bytes32 id) external;
/**
* @notice Returns the list of all registered identifiers.
* @return List of identifiers
*/
function getIds() external view returns (bytes32[] memory);
/**
* @notice Returns the list of all registered identifiers
* @param id Component identifier
* @return The current address represented by an identifier
*/
function getAddress(bytes32 id) external view returns (address);
/**
* @notice Returns the TVL Manager Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return TVL Manager Address
*/
function tvlManagerAddress() external view returns (address);
/**
* @notice Returns the Chainlink Registry Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return Chainlink Registry Address
*/
function chainlinkRegistryAddress() external view returns (address);
/**
* @notice Returns the DAI Pool Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return DAI Pool Address
*/
function daiPoolAddress() external view returns (address);
/**
* @notice Returns the USDC Pool Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return USDC Pool Address
*/
function usdcPoolAddress() external view returns (address);
/**
* @notice Returns the USDT Pool Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return USDT Pool Address
*/
function usdtPoolAddress() external view returns (address);
/**
* @notice Returns the MAPT Pool Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return MAPT Pool Address
*/
function mAptAddress() external view returns (address);
/**
* @notice Returns the LP Account Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return LP Account Address
*/
function lpAccountAddress() external view returns (address);
/**
* @notice Returns the LP Safe Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return LP Safe Address
*/
function lpSafeAddress() external view returns (address);
/**
* @notice Returns the Admin Safe Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return Admin Safe Address
*/
function adminSafeAddress() external view returns (address);
/**
* @notice Returns the Emergency Safe Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return Emergency Safe Address
*/
function emergencySafeAddress() external view returns (address);
/**
* @notice Returns the Oracle Adapter Address
* @dev Not just a helper function, this makes explicit a key ID for the system
* @return Oracle Adapter Address
*/
function oracleAdapterAddress() external view returns (address);
}
/**
SPDX-License-Identifier: UNLICENSED
----------------------------------
---- APY.Finance comments --------
----------------------------------
Due to pragma being fixed at 0.6.6, we had to copy over this contract
and fix the imports.
original path: @chainlink/contracts/src/v0.6/FluxAggregator.sol
npm package version: 0.0.9
*/
pragma solidity 0.6.11;
import "@chainlink/contracts/src/v0.6/Median.sol";
import "@chainlink/contracts/src/v0.6/Owned.sol";
import "@chainlink/contracts/src/v0.6/SafeMath128.sol";
import "@chainlink/contracts/src/v0.6/SafeMath32.sol";
import "@chainlink/contracts/src/v0.6/SafeMath64.sol";
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV2V3Interface.sol";
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorValidatorInterface.sol";
import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol";
import "@chainlink/contracts/src/v0.6/vendor/SafeMath.sol";
/* solhint-disable */
/**
* @title The Prepaid Aggregator contract
* @notice Handles aggregating data pushed in from off-chain, and unlocks
* payment for oracles as they report. Oracles' submissions are gathered in
* rounds, with each round aggregating the submissions for each oracle into a
* single answer. The latest aggregated answer is exposed as well as historical
* answers and their updated at timestamp.
*/
contract FluxAggregator is AggregatorV2V3Interface, Owned {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
}
struct RoundDetails {
int256[] submissions;
uint32 maxSubmissions;
uint32 minSubmissions;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestSubmission;
uint16 index;
address admin;
address pendingAdmin;
}
struct Requester {
bool authorized;
uint32 delay;
uint32 lastStartedRound;
}
struct Funds {
uint128 available;
uint128 allocated;
}
LinkTokenInterface public linkToken;
AggregatorValidatorInterface public validator;
// Round related params
uint128 public paymentAmount;
uint32 public maxSubmissionCount;
uint32 public minSubmissionCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public override decimals;
string public override description;
int256 public immutable minSubmissionValue;
int256 public immutable maxSubmissionValue;
uint256 public constant override version = 3;
/**
* @notice To ensure owner isn't withdrawing required funds as oracles are
* submitting updates, we enforce that the contract maintains a minimum
* reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to
* oracles. (Of course, this doesn't prevent the contract from running out of
* funds without the owner's intervention.)
*/
uint256 private constant RESERVE_ROUNDS = 2;
uint256 private constant MAX_ORACLE_COUNT = 77;
uint32 private constant ROUND_MAX = 2**32 - 1;
uint256 private constant VALIDATOR_GAS_LIMIT = 100000;
// An error specific to the Aggregator V3 Interface, to prevent possible
// confusion around accidentally reading unset values as reported values.
string private constant V3_NO_DATA_ERROR = "No data present";
uint32 private reportingRoundId;
uint32 internal latestRoundId;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
mapping(uint32 => RoundDetails) internal details;
mapping(address => Requester) internal requesters;
address[] private oracleAddresses;
Funds private recordedFunds;
event AvailableFundsUpdated(uint256 indexed amount);
event RoundDetailsUpdated(
uint128 indexed paymentAmount,
uint32 indexed minSubmissionCount,
uint32 indexed maxSubmissionCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event OraclePermissionsUpdated(
address indexed oracle,
bool indexed whitelisted
);
event OracleAdminUpdated(address indexed oracle, address indexed newAdmin);
event OracleAdminUpdateRequested(
address indexed oracle,
address admin,
address newAdmin
);
event SubmissionReceived(
int256 indexed submission,
uint32 indexed round,
address indexed oracle
);
event RequesterPermissionsSet(
address indexed requester,
bool authorized,
uint32 delay
);
event ValidatorUpdated(address indexed previous, address indexed current);
/**
* @notice set up the aggregator with initial configuration
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK)
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
* @param _validator is an optional contract address for validating
* external validation of answers
* @param _minSubmissionValue is an immutable check for a lower bound of what
* submission values are accepted from an oracle
* @param _maxSubmissionValue is an immutable check for an upper bound of what
* submission values are accepted from an oracle
* @param _decimals represents the number of decimals to offset the answer by
* @param _description a short description of what is being reported
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public {
linkToken = LinkTokenInterface(_link);
updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout);
setValidator(_validator);
minSubmissionValue = _minSubmissionValue;
maxSubmissionValue = _maxSubmissionValue;
decimals = _decimals;
description = _description;
rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout)));
}
/**
* @notice called by oracles when they have witnessed a need to update
* @param _roundId is the ID of the round this submission pertains to
* @param _submission is the updated data that the oracle is submitting
*/
function submit(uint256 _roundId, int256 _submission) external {
bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));
require(
_submission >= minSubmissionValue,
"value below minSubmissionValue"
);
require(
_submission <= maxSubmissionValue,
"value above maxSubmissionValue"
);
require(error.length == 0, string(error));
oracleInitializeNewRound(uint32(_roundId));
recordSubmission(_submission, uint32(_roundId));
(bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));
payOracle(uint32(_roundId));
deleteRoundDetails(uint32(_roundId));
if (updated) {
validateAnswer(uint32(_roundId), newAnswer);
}
}
/**
* @notice called by the owner to remove and add new oracles as well as
* update the round related parameters that pertain to total oracle count
* @param _removed is the list of addresses for the new Oracles being removed
* @param _added is the list of addresses for the new Oracles being added
* @param _addedAdmins is the admin addresses for the new respective _added
* list. Only this address is allowed to access the respective oracle's funds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function changeOracles(
address[] calldata _removed,
address[] calldata _added,
address[] calldata _addedAdmins,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay
) external onlyOwner() {
for (uint256 i = 0; i < _removed.length; i++) {
removeOracle(_removed[i]);
}
require(
_added.length == _addedAdmins.length,
"need same oracle and admin count"
);
require(
uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT,
"max oracles allowed"
);
for (uint256 i = 0; i < _added.length; i++) {
addOracle(_added[i], _addedAdmins[i]);
}
updateFutureRounds(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
timeout
);
}
/**
* @notice update the round and payment related parameters for subsequent
* rounds
* @param _paymentAmount is the payment amount for subsequent rounds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function updateFutureRounds(
uint128 _paymentAmount,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay,
uint32 _timeout
) public onlyOwner() {
uint32 oracleNum = oracleCount(); // Save on storage reads
require(
_maxSubmissions >= _minSubmissions,
"max must equal/exceed min"
);
require(oracleNum >= _maxSubmissions, "max cannot exceed total");
require(
oracleNum == 0 || oracleNum > _restartDelay,
"delay cannot exceed total"
);
require(
recordedFunds.available >= requiredReserve(_paymentAmount),
"insufficient funds for payment"
);
if (oracleCount() > 0) {
require(_minSubmissions > 0, "min must be greater than 0");
}
paymentAmount = _paymentAmount;
minSubmissionCount = _minSubmissions;
maxSubmissionCount = _maxSubmissions;
restartDelay = _restartDelay;
timeout = _timeout;
emit RoundDetailsUpdated(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
_timeout
);
}
/**
* @notice the amount of payment yet to be withdrawn by oracles
*/
function allocatedFunds() external view returns (uint128) {
return recordedFunds.allocated;
}
/**
* @notice the amount of future funding available to oracles
*/
function availableFunds() external view returns (uint128) {
return recordedFunds.available;
}
/**
* @notice recalculate the amount of LINK available for payouts
*/
function updateAvailableFunds() public {
Funds memory funds = recordedFunds;
uint256 nowAvailable =
linkToken.balanceOf(address(this)).sub(funds.allocated);
if (funds.available != nowAvailable) {
recordedFunds.available = uint128(nowAvailable);
emit AvailableFundsUpdated(nowAvailable);
}
}
/**
* @notice returns the number of oracles
*/
function oracleCount() public view returns (uint8) {
return uint8(oracleAddresses.length);
}
/**
* @notice returns an array of addresses containing the oracles on contract
*/
function getOracles() external view returns (address[] memory) {
return oracleAddresses;
}
/**
* @notice get the most recently reported answer
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer() public view virtual override returns (int256) {
return rounds[latestRoundId].answer;
}
/**
* @notice get the most recent updated at timestamp
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp() public view virtual override returns (uint256) {
return rounds[latestRoundId].updatedAt;
}
/**
* @notice get the ID of the last updated round
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound() public view virtual override returns (uint256) {
return latestRoundId;
}
/**
* @notice get past rounds answers
* @param _roundId the round number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
virtual
override
returns (int256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].answer;
}
return 0;
}
/**
* @notice get timestamp when an answer was last updated
* @param _roundId the round number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
virtual
override
returns (uint256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].updatedAt;
}
return 0;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet received
* maxSubmissions) answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Round memory r = rounds[uint32(_roundId)];
require(
r.answeredInRound > 0 && validRoundId(_roundId),
V3_NO_DATA_ERROR
);
return (
_roundId,
r.answer,
r.startedAt,
r.updatedAt,
r.answeredInRound
);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values. Consumers are encouraged to
* use this more fully featured method over the "legacy" latestRound/
* latestAnswer/latestTimestamp functions. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time
* out and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return getRoundData(latestRoundId);
}
/**
* @notice query the available amount of LINK for an oracle to withdraw
*/
function withdrawablePayment(address _oracle)
external
view
returns (uint256)
{
return oracles[_oracle].withdrawable;
}
/**
* @notice transfers the oracle's LINK to another address. Can only be called
* by the oracle's admin.
* @param _oracle is the oracle whose LINK is transferred
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawPayment(
address _oracle,
address _recipient,
uint256 _amount
) external {
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
// Safe to downcast _amount because the total amount of LINK is less than 2^128.
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.sub(amount);
recordedFunds.allocated = recordedFunds.allocated.sub(amount);
assert(linkToken.transfer(_recipient, uint256(amount)));
}
/**
* @notice transfers the owner's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
onlyOwner()
{
uint256 available = uint256(recordedFunds.available);
require(
available.sub(requiredReserve(paymentAmount)) >= _amount,
"insufficient reserve funds"
);
require(
linkToken.transfer(_recipient, _amount),
"token transfer failed"
);
updateAvailableFunds();
}
/**
* @notice get the admin address of an oracle
* @param _oracle is the address of the oracle whose admin is being queried
*/
function getAdmin(address _oracle) external view returns (address) {
return oracles[_oracle].admin;
}
/**
* @notice transfer the admin address for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
* @param _newAdmin is the new admin address
*/
function transferAdmin(address _oracle, address _newAdmin) external {
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
oracles[_oracle].pendingAdmin = _newAdmin;
emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin);
}
/**
* @notice accept the admin address transfer for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
*/
function acceptAdmin(address _oracle) external {
require(
oracles[_oracle].pendingAdmin == msg.sender,
"only callable by pending admin"
);
oracles[_oracle].pendingAdmin = address(0);
oracles[_oracle].admin = msg.sender;
emit OracleAdminUpdated(_oracle, msg.sender);
}
/**
* @notice allows non-oracles to request a new round
*/
function requestNewRound() external returns (uint80) {
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(
rounds[current].updatedAt > 0 || timedOut(current),
"prev round must be supersedable"
);
uint32 newRoundId = current.add(1);
requesterInitializeNewRound(newRoundId);
return newRoundId;
}
/**
* @notice allows the owner to specify new non-oracles to start new rounds
* @param _requester is the address to set permissions for
* @param _authorized is a boolean specifying whether they can start new rounds or not
* @param _delay is the number of rounds the requester must wait before starting another round
*/
function setRequesterPermissions(
address _requester,
bool _authorized,
uint32 _delay
) external onlyOwner() {
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit RequesterPermissionsSet(_requester, _authorized, _delay);
}
/**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transferred to the aggregator
* @param _data is mostly ignored. It is checked for length, to be sure
* nothing strange is passed in.
*/
function onTokenTransfer(
address,
uint256,
bytes calldata _data
) external {
require(_data.length == 0, "transfer doesn't accept calldata");
updateAvailableFunds();
}
/**
* @notice a method to provide all current info oracles need. Intended only
* only to be callable by oracles. Not for use by contracts to read state.
* @param _oracle the address to look up information for.
*/
function oracleRoundState(address _oracle, uint32 _queriedRoundId)
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
eligibleForSpecificRound(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
oracleCount(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return oracleRoundStateSuggestRound(_oracle);
}
}
/**
* @notice method to update the address which does external data validation.
* @param _newValidator designates the address of the new validation contract.
*/
function setValidator(address _newValidator) public onlyOwner() {
address previous = address(validator);
if (previous != _newValidator) {
validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
/**
* Private
*/
function initializeNewRound(uint32 _roundId) private {
updateTimedOutRoundInfo(_roundId.sub(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails =
RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);
}
function oracleInitializeNewRound(uint32 _roundId) private {
if (!newRound(_roundId)) return;
uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads
if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;
initializeNewRound(_roundId);
oracles[msg.sender].lastStartedRound = _roundId;
}
function requesterInitializeNewRound(uint32 _roundId) private {
if (!newRound(_roundId)) return;
uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads
require(
_roundId > lastStarted + requesters[msg.sender].delay ||
lastStarted == 0,
"must delay requests"
);
initializeNewRound(_roundId);
requesters[msg.sender].lastStartedRound = _roundId;
}
function updateTimedOutRoundInfo(uint32 _roundId) private {
if (!timedOut(_roundId)) return;
uint32 prevId = _roundId.sub(1);
rounds[_roundId].answer = rounds[prevId].answer;
rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;
rounds[_roundId].updatedAt = uint64(block.timestamp);
delete details[_roundId];
}
function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId)
private
view
returns (bool _eligible)
{
if (rounds[_queriedRoundId].startedAt > 0) {
return
acceptingSubmissions(_queriedRoundId) &&
validateOracleRound(_oracle, _queriedRoundId).length == 0;
} else {
return
delayed(_oracle, _queriedRoundId) &&
validateOracleRound(_oracle, _queriedRoundId).length == 0;
}
}
function oracleRoundStateSuggestRound(address _oracle)
private
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
Round storage round = rounds[0];
OracleStatus storage oracle = oracles[_oracle];
bool shouldSupersede =
oracle.lastReportedRound == reportingRoundId ||
!acceptingSubmissions(reportingRoundId);
// Instead of nudging oracles to submit to the next round, the inclusion of
// the shouldSupersede bool in the if condition pushes them towards
// submitting in a currently open round.
if (supersedable(reportingRoundId) && shouldSupersede) {
_roundId = reportingRoundId.add(1);
round = rounds[_roundId];
_paymentAmount = paymentAmount;
_eligibleToSubmit = delayed(_oracle, _roundId);
} else {
_roundId = reportingRoundId;
round = rounds[_roundId];
_paymentAmount = details[_roundId].paymentAmount;
_eligibleToSubmit = acceptingSubmissions(_roundId);
}
if (validateOracleRound(_oracle, _roundId).length != 0) {
_eligibleToSubmit = false;
}
return (
_eligibleToSubmit,
_roundId,
oracle.latestSubmission,
round.startedAt,
details[_roundId].timeout,
recordedFunds.available,
oracleCount(),
_paymentAmount
);
}
function updateRoundAnswer(uint32 _roundId)
internal
returns (bool, int256)
{
if (
details[_roundId].submissions.length <
details[_roundId].minSubmissions
) {
return (false, 0);
}
int256 newAnswer =
Median.calculateInplace(details[_roundId].submissions);
rounds[_roundId].answer = newAnswer;
rounds[_roundId].updatedAt = uint64(block.timestamp);
rounds[_roundId].answeredInRound = _roundId;
latestRoundId = _roundId;
emit AnswerUpdated(newAnswer, _roundId, now);
return (true, newAnswer);
}
function validateAnswer(uint32 _roundId, int256 _newAnswer) private {
AggregatorValidatorInterface av = validator; // cache storage reads
if (address(av) == address(0)) return;
uint32 prevRound = _roundId.sub(1);
uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;
int256 prevRoundAnswer = rounds[prevRound].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try
av.validate{gas: VALIDATOR_GAS_LIMIT}(
prevAnswerRoundId,
prevRoundAnswer,
_roundId,
_newAnswer
)
{} catch {}
}
function payOracle(uint32 _roundId) private {
uint128 payment = details[_roundId].paymentAmount;
Funds memory funds = recordedFunds;
funds.available = funds.available.sub(payment);
funds.allocated = funds.allocated.add(payment);
recordedFunds = funds;
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(
payment
);
emit AvailableFundsUpdated(funds.available);
}
function recordSubmission(int256 _submission, uint32 _roundId) private {
require(
acceptingSubmissions(_roundId),
"round not accepting submissions"
);
details[_roundId].submissions.push(_submission);
oracles[msg.sender].lastReportedRound = _roundId;
oracles[msg.sender].latestSubmission = _submission;
emit SubmissionReceived(_submission, _roundId, msg.sender);
}
function deleteRoundDetails(uint32 _roundId) private {
if (
details[_roundId].submissions.length <
details[_roundId].maxSubmissions
) return;
delete details[_roundId];
}
function timedOut(uint32 _roundId) private view returns (bool) {
uint64 startedAt = rounds[_roundId].startedAt;
uint32 roundTimeout = details[_roundId].timeout;
return
startedAt > 0 &&
roundTimeout > 0 &&
startedAt.add(roundTimeout) < block.timestamp;
}
function getStartingRound(address _oracle) private view returns (uint32) {
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.add(1);
}
function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId)
private
view
returns (bool)
{
return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0;
}
function requiredReserve(uint256 payment) private view returns (uint256) {
return payment.mul(oracleCount()).mul(RESERVE_ROUNDS);
}
function addOracle(address _oracle, address _admin) private {
require(!oracleEnabled(_oracle), "oracle already enabled");
require(_admin != address(0), "cannot set admin to 0");
require(
oracles[_oracle].admin == address(0) ||
oracles[_oracle].admin == _admin,
"owner cannot overwrite admin"
);
oracles[_oracle].startingRound = getStartingRound(_oracle);
oracles[_oracle].endingRound = ROUND_MAX;
oracles[_oracle].index = uint16(oracleAddresses.length);
oracleAddresses.push(_oracle);
oracles[_oracle].admin = _admin;
emit OraclePermissionsUpdated(_oracle, true);
emit OracleAdminUpdated(_oracle, _admin);
}
function removeOracle(address _oracle) private {
require(oracleEnabled(_oracle), "oracle not enabled");
oracles[_oracle].endingRound = reportingRoundId.add(1);
address tail = oracleAddresses[uint256(oracleCount()).sub(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit OraclePermissionsUpdated(_oracle, false);
}
function validateOracleRound(address _oracle, uint32 _roundId)
private
view
returns (bytes memory)
{
// cache storage reads
uint32 startingRound = oracles[_oracle].startingRound;
uint32 rrId = reportingRoundId;
if (startingRound == 0) return "not enabled oracle";
if (startingRound > _roundId) return "not yet enabled oracle";
if (oracles[_oracle].endingRound < _roundId)
return "no longer allowed oracle";
if (oracles[_oracle].lastReportedRound >= _roundId)
return "cannot report on previous rounds";
if (
_roundId != rrId &&
_roundId != rrId.add(1) &&
!previousAndCurrentUnanswered(_roundId, rrId)
) return "invalid round to report";
if (_roundId != 1 && !supersedable(_roundId.sub(1)))
return "previous round not supersedable";
}
function supersedable(uint32 _roundId) private view returns (bool) {
return rounds[_roundId].updatedAt > 0 || timedOut(_roundId);
}
function oracleEnabled(address _oracle) private view returns (bool) {
return oracles[_oracle].endingRound == ROUND_MAX;
}
function acceptingSubmissions(uint32 _roundId) private view returns (bool) {
return details[_roundId].maxSubmissions != 0;
}
function delayed(address _oracle, uint32 _roundId)
private
view
returns (bool)
{
uint256 lastStarted = oracles[_oracle].lastStartedRound;
return _roundId > lastStarted + restartDelay || lastStarted == 0;
}
function newRound(uint32 _roundId) private view returns (bool) {
return _roundId == reportingRoundId.add(1);
}
function validRoundId(uint256 _roundId) private view returns (bool) {
return _roundId <= ROUND_MAX;
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice Interface for securely interacting with Chainlink aggregators
*/
interface IOracleAdapter {
struct Value {
uint256 value;
uint256 periodEnd;
}
/// @notice Event fired when asset's pricing source (aggregator) is updated
event AssetSourceUpdated(address indexed asset, address indexed source);
/// @notice Event fired when the TVL aggregator address is updated
event TvlSourceUpdated(address indexed source);
/**
* @notice Set the TVL source (aggregator)
* @param source The new TVL source (aggregator)
*/
function emergencySetTvlSource(address source) external;
/**
* @notice Set an asset's price source (aggregator)
* @param asset The asset to change the source of
* @param source The new source (aggregator)
*/
function emergencySetAssetSource(address asset, address source) external;
/**
* @notice Set multiple assets' pricing sources
* @param assets An array of assets (tokens)
* @param sources An array of price sources (aggregators)
*/
function emergencySetAssetSources(
address[] memory assets,
address[] memory sources
) external;
/**
* @notice Retrieve the asset's price from its pricing source
* @param asset The asset address
* @return The price of the asset
*/
function getAssetPrice(address asset) external view returns (uint256);
/**
* @notice Retrieve the deployed TVL from the TVL aggregator
* @return The TVL
*/
function getTvl() external view returns (uint256);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IOracleAdapter} from "./IOracleAdapter.sol";
interface IOverrideOracle is IOracleAdapter {
/**
* @notice Event fired when asset value is set manually
* @param asset The asset that is being overridden
* @param value The new value used for the override
* @param period The number of blocks the override will be active for
* @param periodEnd The block on which the override ends
*/
event AssetValueSet(
address asset,
uint256 value,
uint256 period,
uint256 periodEnd
);
/**
* @notice Event fired when manually submitted asset value is
* invalidated, allowing usual Chainlink pricing.
*/
event AssetValueUnset(address asset);
/**
* @notice Event fired when deployed TVL is set manually
* @param value The new value used for the override
* @param period The number of blocks the override will be active for
* @param periodEnd The block on which the override ends
*/
event TvlSet(uint256 value, uint256 period, uint256 periodEnd);
/**
* @notice Event fired when manually submitted TVL is
* invalidated, allowing usual Chainlink pricing.
*/
event TvlUnset();
/**
* @notice Manually override the asset pricing source with a value
* @param asset The asset that is being overriden
* @param value asset value to return instead of from Chainlink
* @param period length of time, in number of blocks, to use manual override
*/
function emergencySetAssetValue(
address asset,
uint256 value,
uint256 period
) external;
/**
* @notice Revoke manually set value, allowing usual Chainlink pricing
* @param asset address of asset to price
*/
function emergencyUnsetAssetValue(address asset) external;
/**
* @notice Manually override the TVL source with a value
* @param value TVL to return instead of from Chainlink
* @param period length of time, in number of blocks, to use manual override
*/
function emergencySetTvl(uint256 value, uint256 period) external;
/// @notice Revoke manually set value, allowing usual Chainlink pricing
function emergencyUnsetTvl() external;
/// @notice Check if TVL has active manual override
function hasTvlOverride() external view returns (bool);
/**
* @notice Check if asset has active manual override
* @param asset address of the asset
* @return `true` if manual override is active
*/
function hasAssetOverride(address asset) external view returns (bool);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IOracleAdapter} from "./IOracleAdapter.sol";
/**
* @notice For an `IOracleAdapter` that can be locked and unlocked
*/
interface ILockingOracle is IOracleAdapter {
/// @notice Event fired when using the default lock
event DefaultLocked(address locker, uint256 defaultPeriod, uint256 lockEnd);
/// @notice Event fired when using a specified lock period
event Locked(address locker, uint256 activePeriod, uint256 lockEnd);
/// @notice Event fired when changing the default locking period
event DefaultLockPeriodChanged(uint256 newPeriod);
/// @notice Event fired when unlocking the adapter
event Unlocked();
/// @notice Event fired when updating the threshold for stale data
event ChainlinkStalePeriodUpdated(uint256 period);
/// @notice Block price/value retrieval for the default locking duration
function lock() external;
/**
* @notice Block price/value retrieval for the specified duration.
* @param period number of blocks to block retrieving values
*/
function lockFor(uint256 period) external;
/**
* @notice Unblock price/value retrieval. Should only be callable
* by the Emergency Safe.
*/
function emergencyUnlock() external;
/**
* @notice Set the length of time before values can be retrieved.
* @param newPeriod number of blocks before values can be retrieved
*/
function setDefaultLockPeriod(uint256 newPeriod) external;
/**
* @notice Set the length of time before an agg value is considered stale.
* @param chainlinkStalePeriod_ the length of time in seconds
*/
function setChainlinkStalePeriod(uint256 chainlinkStalePeriod_) external;
/**
* @notice Get the length of time, in number of blocks, before values
* can be retrieved.
*/
function defaultLockPeriod() external returns (uint256 period);
/// @notice Check if the adapter is blocked from retrieving values.
function isLocked() external view returns (bool);
}
pragma solidity ^0.6.0;
import "./vendor/SafeMath.sol";
import "./SignedSafeMath.sol";
library Median {
using SignedSafeMath for int256;
int256 constant INT_MAX = 2**255-1;
/**
* @notice Returns the sorted middle, or the average of the two middle indexed items if the
* array has an even number of elements.
* @dev The list passed as an argument isn't modified.
* @dev This algorithm has expected runtime O(n), but for adversarially chosen inputs
* the runtime is O(n^2).
* @param list The list of elements to compare
*/
function calculate(int256[] memory list)
internal
pure
returns (int256)
{
return calculateInplace(copy(list));
}
/**
* @notice See documentation for function calculate.
* @dev The list passed as an argument may be permuted.
*/
function calculateInplace(int256[] memory list)
internal
pure
returns (int256)
{
require(0 < list.length, "list must not be empty");
uint256 len = list.length;
uint256 middleIndex = len / 2;
if (len % 2 == 0) {
int256 median1;
int256 median2;
(median1, median2) = quickselectTwo(list, 0, len - 1, middleIndex - 1, middleIndex);
return SignedSafeMath.avg(median1, median2);
} else {
return quickselect(list, 0, len - 1, middleIndex);
}
}
/**
* @notice Maximum length of list that shortSelectTwo can handle
*/
uint256 constant SHORTSELECTTWO_MAX_LENGTH = 7;
/**
* @notice Select the k1-th and k2-th element from list of length at most 7
* @dev Uses an optimal sorting network
*/
function shortSelectTwo(
int256[] memory list,
uint256 lo,
uint256 hi,
uint256 k1,
uint256 k2
)
private
pure
returns (int256 k1th, int256 k2th)
{
// Uses an optimal sorting network (https://en.wikipedia.org/wiki/Sorting_network)
// for lists of length 7. Network layout is taken from
// http://jgamble.ripco.net/cgi-bin/nw.cgi?inputs=7&algorithm=hibbard&output=svg
uint256 len = hi + 1 - lo;
int256 x0 = list[lo + 0];
int256 x1 = 1 < len ? list[lo + 1] : INT_MAX;
int256 x2 = 2 < len ? list[lo + 2] : INT_MAX;
int256 x3 = 3 < len ? list[lo + 3] : INT_MAX;
int256 x4 = 4 < len ? list[lo + 4] : INT_MAX;
int256 x5 = 5 < len ? list[lo + 5] : INT_MAX;
int256 x6 = 6 < len ? list[lo + 6] : INT_MAX;
if (x0 > x1) {(x0, x1) = (x1, x0);}
if (x2 > x3) {(x2, x3) = (x3, x2);}
if (x4 > x5) {(x4, x5) = (x5, x4);}
if (x0 > x2) {(x0, x2) = (x2, x0);}
if (x1 > x3) {(x1, x3) = (x3, x1);}
if (x4 > x6) {(x4, x6) = (x6, x4);}
if (x1 > x2) {(x1, x2) = (x2, x1);}
if (x5 > x6) {(x5, x6) = (x6, x5);}
if (x0 > x4) {(x0, x4) = (x4, x0);}
if (x1 > x5) {(x1, x5) = (x5, x1);}
if (x2 > x6) {(x2, x6) = (x6, x2);}
if (x1 > x4) {(x1, x4) = (x4, x1);}
if (x3 > x6) {(x3, x6) = (x6, x3);}
if (x2 > x4) {(x2, x4) = (x4, x2);}
if (x3 > x5) {(x3, x5) = (x5, x3);}
if (x3 > x4) {(x3, x4) = (x4, x3);}
uint256 index1 = k1 - lo;
if (index1 == 0) {k1th = x0;}
else if (index1 == 1) {k1th = x1;}
else if (index1 == 2) {k1th = x2;}
else if (index1 == 3) {k1th = x3;}
else if (index1 == 4) {k1th = x4;}
else if (index1 == 5) {k1th = x5;}
else if (index1 == 6) {k1th = x6;}
else {revert("k1 out of bounds");}
uint256 index2 = k2 - lo;
if (k1 == k2) {return (k1th, k1th);}
else if (index2 == 0) {return (k1th, x0);}
else if (index2 == 1) {return (k1th, x1);}
else if (index2 == 2) {return (k1th, x2);}
else if (index2 == 3) {return (k1th, x3);}
else if (index2 == 4) {return (k1th, x4);}
else if (index2 == 5) {return (k1th, x5);}
else if (index2 == 6) {return (k1th, x6);}
else {revert("k2 out of bounds");}
}
/**
* @notice Selects the k-th ranked element from list, looking only at indices between lo and hi
* (inclusive). Modifies list in-place.
*/
function quickselect(int256[] memory list, uint256 lo, uint256 hi, uint256 k)
private
pure
returns (int256 kth)
{
require(lo <= k);
require(k <= hi);
while (lo < hi) {
if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) {
int256 ignore;
(kth, ignore) = shortSelectTwo(list, lo, hi, k, k);
return kth;
}
uint256 pivotIndex = partition(list, lo, hi);
if (k <= pivotIndex) {
// since pivotIndex < (original hi passed to partition),
// termination is guaranteed in this case
hi = pivotIndex;
} else {
// since (original lo passed to partition) <= pivotIndex,
// termination is guaranteed in this case
lo = pivotIndex + 1;
}
}
return list[lo];
}
/**
* @notice Selects the k1-th and k2-th ranked elements from list, looking only at indices between
* lo and hi (inclusive). Modifies list in-place.
*/
function quickselectTwo(
int256[] memory list,
uint256 lo,
uint256 hi,
uint256 k1,
uint256 k2
)
internal // for testing
pure
returns (int256 k1th, int256 k2th)
{
require(k1 < k2);
require(lo <= k1 && k1 <= hi);
require(lo <= k2 && k2 <= hi);
while (true) {
if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) {
return shortSelectTwo(list, lo, hi, k1, k2);
}
uint256 pivotIdx = partition(list, lo, hi);
if (k2 <= pivotIdx) {
hi = pivotIdx;
} else if (pivotIdx < k1) {
lo = pivotIdx + 1;
} else {
assert(k1 <= pivotIdx && pivotIdx < k2);
k1th = quickselect(list, lo, pivotIdx, k1);
k2th = quickselect(list, pivotIdx + 1, hi, k2);
return (k1th, k2th);
}
}
}
/**
* @notice Partitions list in-place using Hoare's partitioning scheme.
* Only elements of list between indices lo and hi (inclusive) will be modified.
* Returns an index i, such that:
* - lo <= i < hi
* - forall j in [lo, i]. list[j] <= list[i]
* - forall j in [i, hi]. list[i] <= list[j]
*/
function partition(int256[] memory list, uint256 lo, uint256 hi)
private
pure
returns (uint256)
{
// We don't care about overflow of the addition, because it would require a list
// larger than any feasible computer's memory.
int256 pivot = list[(lo + hi) / 2];
lo -= 1; // this can underflow. that's intentional.
hi += 1;
while (true) {
do {
lo += 1;
} while (list[lo] < pivot);
do {
hi -= 1;
} while (list[hi] > pivot);
if (lo < hi) {
(list[lo], list[hi]) = (list[hi], list[lo]);
} else {
// Let orig_lo and orig_hi be the original values of lo and hi passed to partition.
// Then, hi < orig_hi, because hi decreases *strictly* monotonically
// in each loop iteration and
// - either list[orig_hi] > pivot, in which case the first loop iteration
// will achieve hi < orig_hi;
// - or list[orig_hi] <= pivot, in which case at least two loop iterations are
// needed:
// - lo will have to stop at least once in the interval
// [orig_lo, (orig_lo + orig_hi)/2]
// - (orig_lo + orig_hi)/2 < orig_hi
return hi;
}
}
}
/**
* @notice Makes an in-memory copy of the array passed in
* @param list Reference to the array to be copied
*/
function copy(int256[] memory list)
private
pure
returns(int256[] memory)
{
int256[] memory list2 = new int256[](list.length);
for (uint256 i = 0; i < list.length; i++) {
list2[i] = list[i];
}
return list2;
}
}
pragma solidity ^0.6.0;
/**
* @title The Owned contract
* @notice A contract with helpers for basic contract ownership.
*/
contract Owned {
address payable public owner;
address private pendingOwner;
event OwnershipTransferRequested(
address indexed from,
address indexed to
);
event OwnershipTransferred(
address indexed from,
address indexed to
);
constructor() public {
owner = msg.sender;
}
/**
* @dev Allows an owner to begin transferring ownership to a new address,
* pending.
*/
function transferOwnership(address _to)
external
onlyOwner()
{
pendingOwner = _to;
emit OwnershipTransferRequested(owner, _to);
}
/**
* @dev Allows an ownership transfer to be completed by the recipient.
*/
function acceptOwnership()
external
{
require(msg.sender == pendingOwner, "Must be proposed owner");
address oldOwner = owner;
owner = msg.sender;
pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/**
* @dev Reverts if called by anyone other than the contract owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Only callable by owner");
_;
}
}
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.
*
* This library is a version of Open Zeppelin's SafeMath, modified to support
* unsigned 128 bit integers.
*/
library SafeMath128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
require(b <= a, "SafeMath: subtraction overflow");
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
// 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;
}
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
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.
*
* This library is a version of Open Zeppelin's SafeMath, modified to support
* unsigned 32 bit integers.
*/
library SafeMath32 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
require(b <= a, "SafeMath: subtraction overflow");
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
// 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;
}
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint32 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(uint32 a, uint32 b) internal pure returns (uint32) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
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.
*
* This library is a version of Open Zeppelin's SafeMath, modified to support
* unsigned 64 bit integers.
*/
library SafeMath64 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint64 a, uint64 b) internal pure returns (uint64) {
uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {
require(b <= a, "SafeMath: subtraction overflow");
uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {
// 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;
}
uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint64 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(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity >=0.6.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
pragma solidity ^0.6.0;
interface AggregatorValidatorInterface {
function validate(
uint256 previousRoundId,
int256 previousAnswer,
uint256 currentRoundId,
int256 currentAnswer
) external returns (bool);
}
pragma solidity ^0.6.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
}
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) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
pragma solidity ^0.6.0;
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on 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 Integer division of two signed integers truncating the quotient, reverts on division by 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 Subtracts two signed integers, reverts on 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 Adds two signed integers, reverts on 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;
}
/**
* @notice Computes average of two signed integers, ensuring that the computation
* doesn't overflow.
* @dev If the result is not an integer, it is rounded towards zero. For example,
* avg(-3, -4) = -3
*/
function avg(int256 _a, int256 _b)
internal
pure
returns (int256)
{
if ((_a < 0 && _b > 0) || (_a > 0 && _b < 0)) {
return add(_a, _b) / 2;
}
int256 remainder = (_a % 2 + _b % 2) / 2;
return add(add(_a / 2, _b / 2), remainder);
}
}
pragma solidity >=0.6.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IErc20Allocation} from "./IErc20Allocation.sol";
import {IChainlinkRegistry} from "./IChainlinkRegistry.sol";
import {IAssetAllocationRegistry} from "./IAssetAllocationRegistry.sol";
import {AssetAllocationBase} from "./AssetAllocationBase.sol";
import {ImmutableAssetAllocation} from "./ImmutableAssetAllocation.sol";
import {Erc20AllocationConstants} from "./Erc20Allocation.sol";
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IReservePool} from "contracts/pool/Imports.sol";
/**
* @notice Facilitate lending liquidity to the LP Account from pools
*/
interface ILpAccountFunder {
/**
* @notice Log when liquidity is lent to the LP Account
* @param poolIds An array of address registry IDs for pools that lent
* @param amounts An array of the amount each pool lent
*/
event FundLpAccount(bytes32[] poolIds, uint256[] amounts);
/**
* @notice Log when liquidity is repaid to the pools
* @param poolIds An array of address registry IDs for pools were repaid
* @param amounts An array of the amount each pool was repaid
*/
event WithdrawFromLpAccount(bytes32[] poolIds, uint256[] amounts);
/**
* @notice Log when liquidity is lent to the LP Account
* @param pools An array of address registry IDs for pools that lent
* @param amounts An array of the amount each pool lent
*/
event EmergencyFundLpAccount(IReservePool[] pools, uint256[] amounts);
/**
* @notice Log when liquidity is repaid to the pools
* @param pools An array of address registry IDs for pools were repaid
* @param amounts An array of the amount each pool was repaid
*/
event EmergencyWithdrawFromLpAccount(
IReservePool[] pools,
uint256[] amounts
);
/**
* @notice Lend liquidity to the LP Account from pools
* @dev Should calculate excess liquidity that can be lent
* @param pools An array of address registry IDs for pools that lent
*/
function fundLpAccount(bytes32[] calldata pools) external;
/**
* @notice Lend liquidity to the LP Account from pools
* @notice Only used in emergencies
* @dev Should only be callable by the Admin Safe
* @dev Can lend any arbitrary amount of liquidity
* @param pools An array of address registry IDs for pools that lent
* @param amounts An array of amounts to borrow from each pool
*/
function emergencyFundLpAccount(
IReservePool[] calldata pools,
uint256[] calldata amounts
) external;
/**
* @notice Repay liquidity borrowed by the LP Account
* @dev Should repay enough to fill up the pools' reserves
* @param pools An array of address registry IDs for pools that were repaid
*/
function withdrawFromLpAccount(bytes32[] calldata pools) external;
/**
* @notice Repay liquidity borrowed by the LP Account
* @notice Only used in emergencies
* @dev Should only be callable by the Admin Safe
* @dev Can repay any arbitrary amount of liquidity
* @param pools An array of address registry IDs for pools that were repaid
* @param amounts An array of amounts to repay to each pool
*/
function emergencyWithdrawFromLpAccount(
IReservePool[] calldata pools,
uint256[] calldata amounts
) external;
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {ILiquidityPoolV2} from "./ILiquidityPoolV2.sol";
/**
* @notice For pools that keep a separate reserve of tokens
*/
interface IReservePool is ILiquidityPoolV2 {
/**
* @notice Log when the percent held in reserve is changed
* @param reservePercentage The new percent held in reserve
*/
event ReservePercentageChanged(uint256 reservePercentage);
/**
* @notice Set a new percent of tokens to hold in reserve
* @param reservePercentage_ The new percent
*/
function setReservePercentage(uint256 reservePercentage_) external;
/**
* @notice Transfer an amount of tokens to the LP Account
* @dev This should only be callable by the `MetaPoolToken`
* @param amount The amount of tokens
*/
function transferToLpAccount(uint256 amount) external;
/**
* @notice Get the amount of tokens missing from the reserve
* @dev A negative value indicates extra tokens not needed for the reserve
* @return The amount of missing tokens
*/
function getReserveTopUpValue() external view returns (int256);
/**
* @notice Get the current percentage of tokens held in reserve
* @return The percent
*/
function reservePercentage() external view returns (uint256);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice For pools that can charge an early withdrawal fee
*/
interface IWithdrawFeePool {
/**
* @notice Log when the fee period changes
* @param feePeriod The new fee period
*/
event FeePeriodChanged(uint256 feePeriod);
/**
* @notice Log when the fee percentage changes
* @param feePercentage The new percentage
*/
event FeePercentageChanged(uint256 feePercentage);
/**
* @notice Set the new fee period
* @param feePeriod_ The new fee period
*/
function setFeePeriod(uint256 feePeriod_) external;
/**
* @notice Set the new fee percentage
* @param feePercentage_ The new percentage
*/
function setFeePercentage(uint256 feePercentage_) external;
/**
* @notice Get the period of time that a withdrawal will be considered early
* @notice An early withdrawal gets charged a fee
* @notice The period starts from the time of the last deposit for an account
* @return The time in seconds
*/
function feePeriod() external view returns (uint256);
/**
* @notice Get the percentage of a withdrawal that is charged as a fee
* @return The percentage
*/
function feePercentage() external view returns (uint256);
/**
* @notice Check if caller will be charged early withdrawal fee
* @return `true` when fee will apply, `false` when it won't
*/
function isEarlyRedeem() external view returns (bool);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice For pools that can be locked and unlocked in emergencies
*/
interface ILockingPool {
/** @notice Log when deposits are locked */
event AddLiquidityLocked();
/** @notice Log when deposits are unlocked */
event AddLiquidityUnlocked();
/** @notice Log when withdrawals are locked */
event RedeemLocked();
/** @notice Log when withdrawals are unlocked */
event RedeemUnlocked();
/** @notice Lock deposits and withdrawals */
function emergencyLock() external;
/** @notice Unlock deposits and withdrawals */
function emergencyUnlock() external;
/** @notice Lock deposits */
function emergencyLockAddLiquidity() external;
/** @notice Unlock deposits */
function emergencyUnlockAddLiquidity() external;
/** @notice Lock withdrawals */
function emergencyLockRedeem() external;
/** @notice Unlock withdrawals */
function emergencyUnlockRedeem() external;
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IDetailedERC20} from "contracts/common/Imports.sol";
/**
* @notice For pools that locked value between accounts
* @dev Shares are accounted for using the `APT` token
*/
interface IPoolToken {
/**
* @notice Log a token deposit
* @param sender Address of the depositor account
* @param token Token deposited
* @param tokenAmount The amount of tokens deposited
* @param aptMintAmount Number of shares received
* @param tokenEthValue Total value of the deposit
* @param totalEthValueLocked Total value of the pool
*/
event DepositedAPT(
address indexed sender,
IDetailedERC20 token,
uint256 tokenAmount,
uint256 aptMintAmount,
uint256 tokenEthValue,
uint256 totalEthValueLocked
);
/**
* @notice Log a token withdrawal
* @param sender Address of the withdrawal account
* @param token Token withdrawn
* @param redeemedTokenAmount The amount of tokens withdrawn
* @param aptRedeemAmount Number of shares redeemed
* @param tokenEthValue Total value of the withdrawal
* @param totalEthValueLocked Total value of the pool
*/
event RedeemedAPT(
address indexed sender,
IDetailedERC20 token,
uint256 redeemedTokenAmount,
uint256 aptRedeemAmount,
uint256 tokenEthValue,
uint256 totalEthValueLocked
);
/**
* @notice Add liquidity for a share of the pool
* @param amount Amount to deposit of the underlying stablecoin
*/
function addLiquidity(uint256 amount) external;
/**
* @notice Redeem shares of the pool to withdraw liquidity
* @param tokenAmount The amount of shares to redeem
*/
function redeem(uint256 tokenAmount) external;
/**
* @notice Determine the share received for a deposit
* @param depositAmount The size of the deposit
* @return The number of shares
*/
function calculateMintAmount(uint256 depositAmount)
external
view
returns (uint256);
/**
* @notice How many tokens can be withdrawn with an amount of shares
* @notice Accounts for early withdrawal fee
* @param aptAmount The amount of shares
* @return The amount of tokens
*/
function getUnderlyerAmountWithFee(uint256 aptAmount)
external
view
returns (uint256);
/**
* @notice How many tokens can be withdrawn with an amount of shares
* @param aptAmount The amount of shares
* @return The amount of tokens
*/
function getUnderlyerAmount(uint256 aptAmount)
external
view
returns (uint256);
/**
* @notice Get the total USD value of an amount of shares
* @param aptAmount The amount of shares
* @return The total USD value of the shares
*/
function getAPTValue(uint256 aptAmount) external view returns (uint256);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IDetailedERC20} from "contracts/common/Imports.sol";
/**
* @notice For contracts that hold tokens and track the value locked
*/
interface ILiquidityPoolV2 {
/**
* @notice The token held by the pool
* @return The token address
*/
function underlyer() external view returns (IDetailedERC20);
/**
* @notice Get the total USD value locked in the pool
* @return The total USD value
*/
function getPoolTotalValue() external view returns (uint256);
/**
* @notice Get the total USD value of an amount of tokens
* @param underlyerAmount The amount of tokens
* @return The total USD value
*/
function getValueFromUnderlyerAmount(uint256 underlyerAmount)
external
view
returns (uint256);
/**
* @notice Get the USD price of the token held by the pool
* @return The price
*/
function getUnderlyerPrice() external view returns (uint256);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
import {IERC20, IDetailedERC20} from "contracts/common/Imports.sol";
/**
* @notice An asset allocation for tokens not stored in a protocol
* @dev `IZap`s and `ISwap`s register these separate from other allocations
* @dev Unlike other asset allocations, new tokens can be added or removed
* @dev Registration can override `symbol` and `decimals` manually because
* they are optional in the ERC20 standard.
*/
interface IErc20Allocation {
/** @notice Log when an ERC20 allocation is registered */
event Erc20TokenRegistered(IERC20 token, string symbol, uint8 decimals);
/** @notice Log when an ERC20 allocation is removed */
event Erc20TokenRemoved(IERC20 token);
/**
* @notice Add a new ERC20 token to the asset allocation
* @dev Should not allow duplicate tokens
* @param token The new token
*/
function registerErc20Token(IDetailedERC20 token) external;
/**
* @notice Add a new ERC20 token to the asset allocation
* @dev Should not allow duplicate tokens
* @param token The new token
* @param symbol Override the token symbol
*/
function registerErc20Token(IDetailedERC20 token, string calldata symbol)
external;
/**
* @notice Add a new ERC20 token to the asset allocation
* @dev Should not allow duplicate tokens
* @param token The new token
* @param symbol Override the token symbol
* @param decimals Override the token decimals
*/
function registerErc20Token(
IERC20 token,
string calldata symbol,
uint8 decimals
) external;
/**
* @notice Remove an ERC20 token from the asset allocation
* @param token The token to remove
*/
function removeErc20Token(IERC20 token) external;
/**
* @notice Check if an ERC20 token is registered
* @param token The token to check
* @return `true` if the token is registered, `false` otherwise
*/
function isErc20TokenRegistered(IERC20 token) external view returns (bool);
/**
* @notice Check if multiple ERC20 tokens are ALL registered
* @param tokens An array of tokens to check
* @return `true` if every token is registered, `false` otherwise
*/
function isErc20TokenRegistered(IERC20[] calldata tokens)
external
view
returns (bool);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
/**
* @notice Interface used by Chainlink to aggregate allocations and compute TVL
*/
interface IChainlinkRegistry {
/**
* @notice Get all IDs from registered asset allocations
* @notice Each ID is a unique asset allocation and token index pair
* @dev Should contain no duplicate IDs
* @return list of all IDs
*/
function getAssetAllocationIds() external view returns (bytes32[] memory);
/**
* @notice Get the LP Account's balance for an asset allocation ID
* @param allocationId The ID to fetch the balance for
* @return The balance for the LP Account
*/
function balanceOf(bytes32 allocationId) external view returns (uint256);
/**
* @notice Get the symbol for an allocation ID's underlying token
* @param allocationId The ID to fetch the symbol for
* @return The underlying token symbol
*/
function symbolOf(bytes32 allocationId)
external
view
returns (string memory);
/**
* @notice Get the decimals for an allocation ID's underlying token
* @param allocationId The ID to fetch the decimals for
* @return The underlying token decimals
*/
function decimalsOf(bytes32 allocationId) external view returns (uint256);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IAssetAllocation} from "contracts/common/Imports.sol";
/**
* @notice For managing a collection of `IAssetAllocation` contracts
*/
interface IAssetAllocationRegistry {
/** @notice Log when an asset allocation is registered */
event AssetAllocationRegistered(IAssetAllocation assetAllocation);
/** @notice Log when an asset allocation is removed */
event AssetAllocationRemoved(string name);
/**
* @notice Add a new asset allocation to the registry
* @dev Should not allow duplicate asset allocations
* @param assetAllocation The new asset allocation
*/
function registerAssetAllocation(IAssetAllocation assetAllocation) external;
/**
* @notice Remove an asset allocation from the registry
* @param name The name of the asset allocation (see `INameIdentifier`)
*/
function removeAssetAllocation(string memory name) external;
/**
* @notice Check if multiple asset allocations are ALL registered
* @param allocationNames An array of asset allocation names
* @return `true` if every allocation is registered, otherwise `false`
*/
function isAssetAllocationRegistered(string[] calldata allocationNames)
external
view
returns (bool);
/**
* @notice Get the registered asset allocation with a given name
* @param name The asset allocation name
* @return The asset allocation
*/
function getAssetAllocation(string calldata name)
external
view
returns (IAssetAllocation);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {IAssetAllocation} from "contracts/common/Imports.sol";
abstract contract AssetAllocationBase is IAssetAllocation {
function numberOfTokens() external view override returns (uint256) {
return tokens().length;
}
function symbolOf(uint8 tokenIndex)
public
view
override
returns (string memory)
{
return tokens()[tokenIndex].symbol;
}
function decimalsOf(uint8 tokenIndex) public view override returns (uint8) {
return tokens()[tokenIndex].decimals;
}
function addressOf(uint8 tokenIndex) public view returns (address) {
return tokens()[tokenIndex].token;
}
function tokens() public view virtual override returns (TokenData[] memory);
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {Address} from "contracts/libraries/Imports.sol";
import {AssetAllocationBase} from "./AssetAllocationBase.sol";
/**
* @notice Asset allocation with underlying tokens that cannot be added/removed
*/
abstract contract ImmutableAssetAllocation is AssetAllocationBase {
using Address for address;
constructor() public {
_validateTokens(_getTokenData());
}
function tokens() public view override returns (TokenData[] memory) {
TokenData[] memory tokens_ = _getTokenData();
return tokens_;
}
/**
* @notice Get the immutable array of underlying `TokenData`
* @dev Should be implemented in child contracts with a hardcoded array
* @return The array of `TokenData`
*/
function _getTokenData() internal pure virtual returns (TokenData[] memory);
/**
* @notice Verifies that a `TokenData` array works with the `TvlManager`
* @dev Reverts when there is invalid `TokenData`
* @param tokens_ The array of `TokenData`
*/
function _validateTokens(TokenData[] memory tokens_) internal view virtual {
// length restriction due to encoding logic for allocation IDs
require(tokens_.length < type(uint8).max, "TOO_MANY_TOKENS");
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i].token;
_validateTokenAddress(token);
string memory symbol = tokens_[i].symbol;
require(bytes(symbol).length != 0, "INVALID_SYMBOL");
}
// TODO: check for duplicate tokens
}
/**
* @notice Verify that a token is a contract
* @param token The token to verify
*/
function _validateTokenAddress(address token) internal view virtual {
require(token.isContract(), "INVALID_ADDRESS");
}
}
// SPDX-License-Identifier: BUSDL-1.1
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import {
IERC20,
IDetailedERC20,
AccessControl,
INameIdentifier
} from "contracts/common/Imports.sol";
import {Address, EnumerableSet} from "contracts/libraries/Imports.sol";
import {IAddressRegistryV2} from "contracts/registry/Imports.sol";
import {IErc20Allocation} from "./IErc20Allocation.sol";
import {AssetAllocationBase} from "./AssetAllocationBase.sol";
abstract contract Erc20AllocationConstants is INameIdentifier {
string public constant override NAME = "erc20Allocation";
}
contract Erc20Allocation is
IErc20Allocation,
AssetAllocationBase,
Erc20AllocationConstants,
AccessControl
{
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet private _tokenAddresses;
mapping(address => TokenData) private _tokenToData;
constructor(address addressRegistry_) public {
require(addressRegistry_.isContract(), "INVALID_ADDRESS_REGISTRY");
IAddressRegistryV2 addressRegistry =
IAddressRegistryV2(addressRegistry_);
_setupRole(DEFAULT_ADMIN_ROLE, addressRegistry.emergencySafeAddress());
_setupRole(CONTRACT_ROLE, addressRegistry.mAptAddress());
_setupRole(ADMIN_ROLE, addressRegistry.adminSafeAddress());
}
function registerErc20Token(IDetailedERC20 token)
external
override
onlyAdminOrContractRole
{
string memory symbol = token.symbol();
uint8 decimals = token.decimals();
_registerErc20Token(token, symbol, decimals);
}
function registerErc20Token(IDetailedERC20 token, string calldata symbol)
external
override
onlyAdminRole
{
uint8 decimals = token.decimals();
_registerErc20Token(token, symbol, decimals);
}
function registerErc20Token(
IERC20 token,
string calldata symbol,
uint8 decimals
) external override onlyAdminRole {
_registerErc20Token(token, symbol, decimals);
}
function removeErc20Token(IERC20 token) external override onlyAdminRole {
_tokenAddresses.remove(address(token));
delete _tokenToData[address(token)];
emit Erc20TokenRemoved(token);
}
function isErc20TokenRegistered(IERC20 token)
external
view
override
returns (bool)
{
return _tokenAddresses.contains(address(token));
}
function isErc20TokenRegistered(IERC20[] calldata tokens)
external
view
override
returns (bool)
{
uint256 length = tokens.length;
for (uint256 i = 0; i < length; i++) {
if (!_tokenAddresses.contains(address(tokens[i]))) {
return false;
}
}
return true;
}
function balanceOf(address account, uint8 tokenIndex)
external
view
override
returns (uint256)
{
address token = addressOf(tokenIndex);
return IERC20(token).balanceOf(account);
}
function tokens() public view override returns (TokenData[] memory) {
TokenData[] memory _tokens = new TokenData[](_tokenAddresses.length());
for (uint256 i = 0; i < _tokens.length; i++) {
address tokenAddress = _tokenAddresses.at(i);
_tokens[i] = _tokenToData[tokenAddress];
}
return _tokens;
}
function _registerErc20Token(
IERC20 token,
string memory symbol,
uint8 decimals
) internal {
require(address(token).isContract(), "INVALID_ADDRESS");
require(bytes(symbol).length != 0, "INVALID_SYMBOL");
_tokenAddresses.add(address(token));
_tokenToData[address(token)] = TokenData(
address(token),
symbol,
decimals
);
emit Erc20TokenRegistered(token, symbol, decimals);
}
}
| * @notice Get the immutable array of underlying `TokenData` @dev Should be implemented in child contracts with a hardcoded array @return The array of `TokenData`/* @notice Verifies that a `TokenData` array works with the `TvlManager` @dev Reverts when there is invalid `TokenData` @param tokens_ The array of `TokenData`/ length restriction due to encoding logic for allocation IDs | function _getTokenData() internal pure virtual returns (TokenData[] memory);
function _validateTokens(TokenData[] memory tokens_) internal view virtual {
require(tokens_.length < type(uint8).max, "TOO_MANY_TOKENS");
for (uint256 i = 0; i < tokens_.length; i++) {
address token = tokens_[i].token;
_validateTokenAddress(token);
string memory symbol = tokens_[i].symbol;
require(bytes(symbol).length != 0, "INVALID_SYMBOL");
}
| 281,326 | [
1,
967,
326,
11732,
526,
434,
6808,
1375,
1345,
751,
68,
225,
9363,
506,
8249,
316,
1151,
20092,
598,
279,
7877,
24808,
526,
327,
1021,
526,
434,
1375,
1345,
751,
68,
19,
225,
6160,
5032,
716,
279,
1375,
1345,
751,
68,
526,
6330,
598,
326,
1375,
56,
10872,
1318,
68,
225,
868,
31537,
1347,
1915,
353,
2057,
1375,
1345,
751,
68,
225,
2430,
67,
1021,
526,
434,
1375,
1345,
751,
68,
19,
769,
9318,
6541,
358,
2688,
4058,
364,
13481,
7115,
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,
565,
445,
389,
588,
1345,
751,
1435,
2713,
16618,
5024,
1135,
261,
1345,
751,
8526,
3778,
1769,
203,
203,
565,
445,
389,
5662,
5157,
12,
1345,
751,
8526,
3778,
2430,
67,
13,
2713,
1476,
5024,
288,
203,
3639,
2583,
12,
7860,
27799,
2469,
411,
618,
12,
11890,
28,
2934,
1896,
16,
315,
4296,
51,
67,
24177,
67,
8412,
55,
8863,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
2430,
27799,
2469,
31,
277,
27245,
288,
203,
5411,
1758,
1147,
273,
2430,
67,
63,
77,
8009,
2316,
31,
203,
5411,
389,
5662,
1345,
1887,
12,
2316,
1769,
203,
5411,
533,
3778,
3273,
273,
2430,
67,
63,
77,
8009,
7175,
31,
203,
5411,
2583,
12,
3890,
12,
7175,
2934,
2469,
480,
374,
16,
315,
9347,
67,
22093,
8863,
203,
3639,
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
] |
// Sources flattened with hardhat v2.5.0 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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;
// 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-upgradeable/proxy/[email protected]
// 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) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File contracts/upgrades/ContextUpgradeable.sol
pragma solidity ^0.7.6;
/**
* @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;
}
// File contracts/upgrades/PausableUpgradeable.sol
pragma solidity ^0.7.6;
/**
* @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;
}
// File contracts/upgrades/access/OwnableUpgradeable.sol
pragma solidity ^0.7.6;
abstract contract OwnableUpgradeable is
Initializable,
PausableUpgradeable
{
address public _owner;
address public _admin;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
function __Ownable_init(address ownerAddress) public initializer {
__Ownable_unchained_init(ownerAddress);
__Pausable_init();
}
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_unchained_init(address ownerAddress) internal {
_owner = _msgSender();
_admin = ownerAddress;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(
_owner == _msgSender(),
"Ownable: caller is not the owner"
);
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyAdmin() {
require(
_admin == _msgSender(),
"Ownable: caller is not the Admin"
);
_;
}
/**
* @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 onlyAdmin {
emit OwnershipTransferred(_owner, _admin);
_owner = _admin;
}
/**
* @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;
}
// File contracts/access/Context.sol
pragma solidity ^0.7.6;
/*
* @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 contracts/access/Pausable.sol
pragma solidity >=0.6.0 <=0.8.0;
/**
* @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());
}
}
// File contracts/access/Ownable.sol
pragma solidity >=0.6.0 <=0.8.0;
abstract contract Ownable is Pausable {
address public _owner;
address public _admin;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor(address ownerAddress) {
_owner = ownerAddress;
_admin = ownerAddress;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(
_owner == _msgSender(),
"Ownable: caller is not the owner"
);
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyAdmin() {
require(
_admin == _msgSender(),
"Ownable: caller is not the Admin"
);
_;
}
/**
* @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 onlyAdmin {
emit OwnershipTransferred(_owner, _admin);
_owner = _admin;
}
/**
* @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 contracts/abstract/CohortStaking.sol
pragma solidity ^0.7.6;
abstract contract CohortStaking {
struct tokenInfo {
bool isExist;
uint8 decimal;
uint256 userMinStake;
uint256 userMaxStake;
uint256 totalMaxStake;
uint256 lockableDays;
bool optionableStatus;
}
mapping(address => tokenInfo) public tokenDetails;
mapping(address => uint256) public totalStaking;
mapping(address => address[]) public tokensSequenceList;
mapping(address => mapping(address => uint256))
public tokenDailyDistribution;
mapping(address => mapping(address => bool))
public tokenBlockedStatus;
uint256 public refPercentage;
uint256 public poolStartTime;
uint256 public stakeDuration;
function viewStakingDetails(address _user)
public
view
virtual
returns (
address[] memory,
address[] memory,
bool[] memory,
uint256[] memory,
uint256[] memory,
uint256[] memory
);
function safeWithdraw(address tokenAddress, uint256 amount)
public
virtual;
function transferOwnership(address newOwner) public virtual;
}
// File contracts/libraries/SafeMath.sol
pragma solidity ^0.7.6;
/**
* @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;
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 contracts/interfaces/IERC20.sol
pragma solidity ^0.7.6;
/**
* @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 contracts/interfaces/ICohort.sol
pragma solidity ^0.7.6;
interface ICohort {
function setupCohort(uint256[] memory _intervalDays, bool _isSwapfy)
external
returns (bool);
}
// File contracts/Cohort.sol
pragma solidity ^0.7.6;
/**
* @title Unifarm Cohort Unstake Handler Contract
* @author Opendefi by OroPocket
*/
contract Cohort is Ownable, ICohort {
/// @notice LockableToken struct for storing token lockable details
struct LockableTokens {
uint256 lockableDays;
bool optionableStatus;
}
/// @notice Wrappers over Solidity's arithmetic operations
using SafeMath for uint256;
/// @notice totalStaking of a specfic tokenAddress.
mapping(address => uint256) public totalUnStaking;
/// @notice tokens old to new token swap
mapping(address => address) public tokens;
/// @notice unStakeStatus of a user.
mapping(address => mapping(uint256 => bool)) public unStakeStatus;
/// @notice lockable token mapping
mapping(address => LockableTokens) public lockableDetails;
/// @notice cohort instance.
CohortStaking public cohort;
/// @notice DAYS is equal to 86400.
uint256 public DAYS = 1 days;
/// @notice HOURS is equal to 3600.
uint256 public HOURS = 1 hours;
/// @notice intervalDays
uint256[] public intervalDays;
/// @notice poolStartTime
uint256 public poolStartTime;
/// @notice stakeDuration
uint256 public stakeDuration;
/// @notice isSwapify
bool public swapiFy;
/// @notice factory
address public factory;
event LockableTokenDetails(
address indexed tokenAddress,
uint256 lockableDys,
bool optionalbleStatus,
uint256 updatedTime
);
event WithdrawDetails(
address indexed tokenAddress,
uint256 withdrawalAmount,
uint256 time
);
event Claim(
address indexed userAddress,
address indexed stakedTokenAddress,
address indexed tokenAddress,
uint256 claimRewards,
uint256 time
);
event UnStake(
address indexed userAddress,
address indexed unStakedtokenAddress,
uint256 unStakedAmount,
uint256 time,
uint256 stakeId
);
event ReferralEarn(
address indexed userAddress,
address indexed callerAddress,
address indexed rewardTokenAddress,
uint256 rewardAmount,
uint256 time
);
event IntervalDaysDetails(uint256[] updatedIntervals, uint256 time);
/**
* @notice construct the cohort unstake handler.
* @param cohortAddress specfic cohortAddress.
* @param ownerAddress owner Address of a cohort.
*/
constructor(
address cohortAddress,
address ownerAddress,
address factoryAddress
) Ownable(ownerAddress) {
require(
cohortAddress != address(0),
"Cohort: invalid cohortAddress"
);
cohort = CohortStaking(cohortAddress);
factory = factoryAddress;
}
function setupCohort(uint256[] memory _intervalDays, bool _isSwapfy)
external
override
returns (bool)
{
require(_msgSender() == factory, "Cohort: permission denied");
swapiFy = _isSwapfy;
poolStartTime = cohort.poolStartTime();
stakeDuration = cohort.stakeDuration();
updateIntervalDays(_intervalDays);
return true;
}
// make sure about ownership things before call this function.
function init(address[] memory tokenAddress)
external
onlyOwner
returns (bool)
{
for (uint256 i = 0; i < tokenAddress.length; i++) {
transferFromCohort(tokenAddress[i]);
}
return true;
}
function transferFromCohort(address tokenAddress) internal {
uint256 bal = IERC20(tokenAddress).balanceOf(address(cohort));
if (bal > 0) cohort.safeWithdraw(tokenAddress, bal);
}
function updateCohort(address _newCohortAddress)
external
onlyOwner
returns (bool)
{
cohort = CohortStaking(_newCohortAddress);
return true;
}
function setSwapTokens(
address[] memory oldTokenAddresses,
address[] memory newTokenAddresses
) external onlyOwner returns (bool) {
require(
oldTokenAddresses.length == newTokenAddresses.length,
"Invalid Input Tokens"
);
for (uint8 m = 0; m < oldTokenAddresses.length; m++) {
tokens[oldTokenAddresses[m]] = newTokenAddresses[m];
}
return true;
}
function updateTotalUnStaking(
address[] memory tokenAddresses,
uint256[] memory overAllUnStakedTokens
) external onlyOwner returns (bool) {
require(
tokenAddresses.length == overAllUnStakedTokens.length,
"Cohort: Invalid Inputs"
);
for (uint8 n = 0; n < tokenAddresses.length; n++) {
require(
tokenAddresses[n] != address(0),
"Cohort: invalid poolAddress"
);
require(
overAllUnStakedTokens[n] > 0,
"Cohort: emptied overAllStaked"
);
totalUnStaking[tokenAddresses[n]] = overAllUnStakedTokens[n];
}
return true;
}
function updateIntervalDays(uint256[] memory _interval) public {
require(
_msgSender() == factory || _msgSender() == _owner,
"Cohort: permission denied"
);
intervalDays = new uint256[](0);
for (uint8 i = 0; i < _interval.length; i++) {
uint256 noD = stakeDuration.div(DAYS);
require(noD > _interval[i], "Invalid Interval Day");
intervalDays.push(_interval[i]);
}
emit IntervalDaysDetails(intervalDays, block.timestamp);
}
function lockableToken(
address tokenAddress,
uint8 lockableStatus,
uint256 lockedDays,
bool optionableStatus
) external onlyOwner {
require(
lockableStatus == 1 ||
lockableStatus == 2 ||
lockableStatus == 3,
"Invalid Lockable Status"
);
(bool tokenExist, , , , , , ) = cohort.tokenDetails(tokenAddress);
require(tokenExist == true, "Token Not Exist");
if (lockableStatus == 1) {
lockableDetails[tokenAddress].lockableDays = block
.timestamp
.add(lockedDays);
} else if (lockableStatus == 2)
lockableDetails[tokenAddress].lockableDays = 0;
else if (lockableStatus == 3)
lockableDetails[tokenAddress]
.optionableStatus = optionableStatus;
emit LockableTokenDetails(
tokenAddress,
lockableDetails[tokenAddress].lockableDays,
lockableDetails[tokenAddress].optionableStatus,
block.timestamp
);
}
function reclaimOwnership(address newOwner)
external
onlyOwner
returns (bool)
{
cohort.transferOwnership(newOwner);
return true;
}
function safeWithdraw(address tokenAddress, uint256 amount)
external
onlyOwner
{
require(
IERC20(tokenAddress).balanceOf(address(this)) >= amount,
"SAFEWITHDRAW: Insufficient Balance"
);
require(
IERC20(tokenAddress).transfer(_owner, amount) == true,
"SAFEWITHDRAW: Transfer failed"
);
emit WithdrawDetails(tokenAddress, amount, block.timestamp);
}
function getTokenAddress(address tokenAddress)
internal
view
returns (address)
{
if (swapiFy) {
address newAddress = tokens[tokenAddress] == address(0)
? tokenAddress
: tokens[tokenAddress];
return (newAddress);
} else {
return (tokenAddress);
}
}
/**
* @notice Claim accumulated rewards
* @param userAddress user Address through he staked.
* @param stakeId Stake ID of the user
* @param totalStake total Staking.
*/
function claimRewards(
address userAddress,
uint256 stakeId,
uint256 totalStake
) internal {
// Local variables
uint256 interval;
uint256 endOfProfit;
(
address[] memory referrar,
address[] memory tokenAddresses,
,
,
uint256[] memory stakedAmount,
uint256[] memory startTime
) = cohort.viewStakingDetails(userAddress);
interval = poolStartTime.add(stakeDuration);
// Interval calculation
if (interval > block.timestamp) endOfProfit = block.timestamp;
else endOfProfit = poolStartTime.add(stakeDuration);
interval = endOfProfit.sub(startTime[stakeId]);
uint256 refPercentage = cohort.refPercentage();
uint256[3] memory stakeData;
stakeData[0] = (stakedAmount[stakeId]);
stakeData[1] = (totalStake);
stakeData[2] = (refPercentage);
// Reward calculation
if (interval >= HOURS)
_rewardCalculation(
userAddress,
tokenAddresses[stakeId],
referrar[stakeId],
stakeData,
interval
);
}
function _rewardCalculation(
address userAddress,
address tokenAddress,
address referrer,
uint256[3] memory stakingData,
uint256 interval
) internal {
uint256 rewardsEarned;
uint256 refEarned;
uint256[2] memory noOfDays;
noOfDays[1] = interval.div(HOURS);
noOfDays[0] = interval.div(DAYS);
rewardsEarned = noOfDays[1].mul(
getOneDayReward(
stakingData[0],
tokenAddress,
tokenAddress,
stakingData[1]
)
);
address stakedToken = getTokenAddress(tokenAddress);
// Referrer Earning
if (referrer != address(0)) {
refEarned = (rewardsEarned.mul(stakingData[2])).div(100 ether);
rewardsEarned = rewardsEarned.sub(refEarned);
require(
IERC20(stakedToken).transfer(referrer, refEarned) == true,
"Transfer Failed"
);
emit ReferralEarn(
referrer,
_msgSender(),
stakedToken,
refEarned,
block.timestamp
);
}
// Rewards Send
sendToken(userAddress, stakedToken, stakedToken, rewardsEarned);
uint8 i = 1;
while (i < intervalDays.length) {
if (noOfDays[0] >= intervalDays[i]) {
uint256 reductionHours = (intervalDays[i].sub(1)).mul(24);
uint256 balHours = noOfDays[1].sub(reductionHours);
address rewardToken = cohort.tokensSequenceList(
tokenAddress,
i
);
if (
rewardToken != tokenAddress &&
cohort.tokenBlockedStatus(tokenAddress, rewardToken) ==
false
) {
rewardsEarned = balHours.mul(
getOneDayReward(
stakingData[0],
tokenAddress,
rewardToken,
stakingData[1]
)
);
address rewardToken1 = getTokenAddress(rewardToken);
// Referrer Earning
if (referrer != address(0)) {
refEarned = (rewardsEarned.mul(stakingData[2])).div(
100 ether
);
rewardsEarned = rewardsEarned.sub(refEarned);
require(
IERC20(rewardToken1).transfer(referrer, refEarned) ==
true,
"Transfer Failed"
);
emit ReferralEarn(
referrer,
_msgSender(),
rewardToken1,
refEarned,
block.timestamp
);
}
// Rewards Send
sendToken(
userAddress,
tokenAddress,
rewardToken1,
rewardsEarned
);
}
i = i + 1;
} else {
break;
}
}
}
/**
* @notice Get rewards for one day
* @param stakedAmount Stake amount of the user
* @param stakedToken Staked token address of the user
* @param rewardToken Reward token address
* @return reward One dayh reward for the user
*/
function getOneDayReward(
uint256 stakedAmount,
address stakedToken,
address rewardToken,
uint256 totalStake
) public view returns (uint256 reward) {
reward = (
stakedAmount.mul(
cohort.tokenDailyDistribution(stakedToken, rewardToken)
)
).div(totalStake);
}
/**
* @notice Get rewards for one day
* @param stakedToken Stake amount of the user
* @param tokenAddress Reward token address
* @param amount Amount to be transferred as reward
*/
function sendToken(
address userAddress,
address stakedToken,
address tokenAddress,
uint256 amount
) internal {
// Checks
if (tokenAddress != address(0)) {
require(
IERC20(tokenAddress).balanceOf(address(this)) >= amount,
"SEND : Insufficient Reward Balance"
);
require(
IERC20(tokenAddress).transfer(userAddress, amount),
"Transfer failed"
);
// Emit state changes
emit Claim(
userAddress,
stakedToken,
tokenAddress,
amount,
block.timestamp
);
}
}
function getTotalStaking(address tokenAddress)
public
view
returns (uint256)
{
uint256 totalStaking = cohort.totalStaking(tokenAddress);
uint256 actualStaking = totalStaking.add(
totalUnStaking[tokenAddress]
);
return actualStaking;
}
/**
* @notice Unstake and claim rewards
* @param stakeId Stake ID of the user
*/
function unStake(address userAddress, uint256 stakeId)
external
whenNotPaused
returns (bool)
{
require(
_msgSender() == userAddress || _msgSender() == _owner,
"UNSTAKE: Invalid User Entry"
);
// view the staking details
(
,
address[] memory tokenAddress,
bool[] memory isActive,
,
uint256[] memory stakedAmount,
uint256[] memory startTime
) = cohort.viewStakingDetails(userAddress);
uint256 totalStaking = getTotalStaking(tokenAddress[stakeId]);
address stakedToken = getTokenAddress(tokenAddress[stakeId]);
// lockableDays check
require(
lockableDetails[stakedToken].lockableDays <= block.timestamp,
"UNSTAKE: Token Locked"
);
// optional lock check
if (lockableDetails[stakedToken].optionableStatus == true)
require(
startTime[stakeId].add(stakeDuration) <= block.timestamp,
"UNSTAKE: Locked in optional lock"
);
// Checks
require(
stakedAmount[stakeId] > 0 &&
isActive[stakeId] == true &&
unStakeStatus[userAddress][stakeId] == false,
"UNSTAKE : Already Claimed (or) Insufficient Staked"
);
// update the state
unStakeStatus[userAddress][stakeId] = true;
// Balance check
require(
IERC20(stakedToken).balanceOf(address(this)) >=
stakedAmount[stakeId],
"UNSTAKE : Insufficient Balance"
);
// Transfer staked token back to user
IERC20(stakedToken).transfer(userAddress, stakedAmount[stakeId]);
claimRewards(userAddress, stakeId, totalStaking);
// Emit state changes
emit UnStake(
userAddress,
stakedToken,
stakedAmount[stakeId],
block.timestamp,
stakeId
);
return true;
}
function emergencyUnstake(
uint256 stakeId,
address userAddress,
address[] memory rewardtokens,
uint256[] memory amount
) external onlyOwner {
// view the staking details
(
address[] memory referrer,
address[] memory tokenAddress,
bool[] memory isActive,
,
uint256[] memory stakedAmount,
) = cohort.viewStakingDetails(userAddress);
require(
stakedAmount[stakeId] > 0 &&
isActive[stakeId] == true &&
unStakeStatus[userAddress][stakeId] == false,
"EMERGENCY : Already Claimed (or) Insufficient Staked"
);
address stakedToken = getTokenAddress(tokenAddress[stakeId]);
// Balance check
require(
IERC20(stakedToken).balanceOf(address(this)) >=
stakedAmount[stakeId],
"EMERGENCY : Insufficient Balance"
);
unStakeStatus[userAddress][stakeId] = true;
IERC20(stakedToken).transfer(userAddress, stakedAmount[stakeId]);
uint256 refPercentage = cohort.refPercentage();
for (uint256 i; i < rewardtokens.length; i++) {
uint256 rewardsEarned = amount[i];
if (referrer[stakeId] != address(0)) {
uint256 refEarned = (rewardsEarned.mul(refPercentage)).div(
100 ether
);
rewardsEarned = rewardsEarned.sub(refEarned);
require(
IERC20(rewardtokens[i]).transfer(
referrer[stakeId],
refEarned
),
"EMERGENCY : Transfer Failed"
);
emit ReferralEarn(
referrer[stakeId],
userAddress,
rewardtokens[i],
refEarned,
block.timestamp
);
}
sendToken(
userAddress,
tokenAddress[stakeId],
rewardtokens[i],
rewardsEarned
);
}
// Emit state changes
emit UnStake(
userAddress,
tokenAddress[stakeId],
stakedAmount[stakeId],
block.timestamp,
stakeId
);
}
function pause() external onlyOwner returns (bool) {
_pause();
return true;
}
function unpause() external onlyOwner returns (bool) {
_unpause();
return true;
}
}
// File contracts/CohortFactory.sol
pragma solidity ^0.7.6;
contract CohortFactory is Initializable, OwnableUpgradeable {
/// @notice public mapping for storing unstakeHandler Address.
mapping(address => address) public unStakeHandlers;
/// @notice CohortDeployment event
event CohortDeployment(
address indexed deployer,
address indexed cohort,
address poolAddress,
uint256 when
);
/// @notice initialize.
function __CohortFactory_init() public initializer {
__Ownable_init(_msgSender());
}
function deploy(
address cohort,
bool isSwapfy,
uint256[] memory intervalDays
) external onlyOwner returns (address) {
require(
cohort != address(0),
"CohortFactory: invalid cohort address."
);
address poolAddress = address(
new Cohort(cohort, _msgSender(), address(this))
);
unStakeHandlers[cohort] = poolAddress;
// setup cohort
ICohort(poolAddress).setupCohort(intervalDays, isSwapfy);
emit CohortDeployment(
_owner,
cohort,
unStakeHandlers[cohort],
block.timestamp
);
return poolAddress;
}
uint256[49] private __gap;
} | @notice LockableToken struct for storing token lockable details | struct LockableTokens {
uint256 lockableDays;
bool optionableStatus;
}
event LockableTokenDetails(
address indexed tokenAddress,
uint256 lockableDys,
bool optionalbleStatus,
uint256 updatedTime
);
event WithdrawDetails(
address indexed tokenAddress,
uint256 withdrawalAmount,
uint256 time
);
event Claim(
address indexed userAddress,
address indexed stakedTokenAddress,
address indexed tokenAddress,
uint256 claimRewards,
uint256 time
);
event UnStake(
address indexed userAddress,
address indexed unStakedtokenAddress,
uint256 unStakedAmount,
uint256 time,
uint256 stakeId
);
event ReferralEarn(
address indexed userAddress,
address indexed callerAddress,
address indexed rewardTokenAddress,
uint256 rewardAmount,
uint256 time
);
event IntervalDaysDetails(uint256[] updatedIntervals, uint256 time);
constructor(
address cohortAddress,
address ownerAddress,
address factoryAddress
| 12,205,931 | [
1,
2531,
429,
1345,
1958,
364,
15729,
1147,
2176,
429,
3189,
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,
225,
1958,
3488,
429,
5157,
288,
203,
565,
2254,
5034,
2176,
429,
9384,
31,
203,
565,
1426,
1456,
429,
1482,
31,
203,
225,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
225,
871,
3488,
429,
1345,
3790,
12,
203,
565,
1758,
8808,
1147,
1887,
16,
203,
565,
2254,
5034,
2176,
429,
40,
1900,
16,
203,
565,
1426,
3129,
7119,
1482,
16,
203,
565,
2254,
5034,
3526,
950,
203,
225,
11272,
203,
203,
225,
871,
3423,
9446,
3790,
12,
203,
565,
1758,
8808,
1147,
1887,
16,
203,
565,
2254,
5034,
598,
9446,
287,
6275,
16,
203,
565,
2254,
5034,
813,
203,
225,
11272,
203,
203,
225,
871,
18381,
12,
203,
565,
1758,
8808,
729,
1887,
16,
203,
565,
1758,
8808,
384,
9477,
1345,
1887,
16,
203,
565,
1758,
8808,
1147,
1887,
16,
203,
565,
2254,
5034,
7516,
17631,
14727,
16,
203,
565,
2254,
5034,
813,
203,
225,
11272,
203,
203,
225,
871,
1351,
510,
911,
12,
203,
565,
1758,
8808,
729,
1887,
16,
203,
565,
1758,
8808,
640,
510,
9477,
2316,
1887,
16,
203,
565,
2254,
5034,
640,
510,
9477,
6275,
16,
203,
565,
2254,
5034,
813,
16,
203,
565,
2254,
5034,
384,
911,
548,
203,
225,
11272,
203,
203,
225,
871,
3941,
29084,
41,
1303,
12,
203,
565,
1758,
8808,
729,
1887,
16,
203,
565,
1758,
8808,
4894,
1887,
16,
203,
565,
1758,
8808,
19890,
1345,
1887,
16,
203,
565,
2254,
5034,
19890,
6275,
16,
203,
565,
2254,
5034,
813,
203,
225,
11272,
203,
203,
225,
2
] |
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
interface ISwapFeeRewardWithRB {
function accrueRBFromMarket(
address account,
address fromToken,
uint256 amount
) external;
}
interface ISmartChefMarket {
function updateStakedTokens(address _user, uint256 amount) external;
}
//BSW, BNB, WBNB, BUSD, USDT
contract Market is ReentrancyGuard, Ownable, Pausable {
using SafeERC20 for IERC20;
enum Side {
Sell,
Buy
}
enum OfferStatus {
Open,
Accepted,
Cancelled
}
struct RoyaltyStr {
uint32 rate;
address receiver;
bool enable;
}
uint256 constant MAX_DEFAULT_FEE = 1000; // max fee 10% (base 10000)
uint256 public defaultFee = 100; //in base 10000 1%
uint8 public maxUserTokenOnSellToReward = 3; //max count sell offers of nftForAccrualRB on which Rb accrual
uint256 rewardDistributionSeller = 50; //Distribution reward between seller and buyer. Base 100
address public treasuryAddress;
ISwapFeeRewardWithRB feeRewardRB;
ISmartChefMarket smartChefMarket;
bool feeRewardRBIsEnabled = false; // Enable/disable accrue RB reward for trade NFT tokens from nftForAccrualRB list
bool placementRewardEnabled = false; //Enable rewards for place NFT tokens on market
Offer[] public offers;
mapping(IERC721 => mapping(uint256 => uint256)) public tokenSellOffers; // nft => tokenId => id
mapping(address => mapping(IERC721 => mapping(uint256 => uint256))) public userBuyOffers; // user => nft => tokenId => id
mapping(address => bool) public nftBlacklist; //add tokens on blackList
mapping(address => bool) public nftForAccrualRB; //add tokens on which RobiBoost is accrual
mapping(address => bool) public dealTokensWhitelist;
mapping(address => uint256) public userFee; //User trade fee. if Zero - fee by default
mapping(address => uint256) public tokensCount; //User`s number of tokens on sale: user => count
mapping(address => RoyaltyStr) public royalty; //Royalty for NFT creator. NFTToken => royalty (base 10000)
struct Offer {
uint256 tokenId;
uint256 price;
IERC20 dealToken;
IERC721 nft;
address user;
address acceptUser;
OfferStatus status;
Side side;
}
event NewOffer(
address indexed user,
IERC721 indexed nft,
uint256 indexed tokenId,
address dealToken,
uint256 price,
Side side,
uint256 id
);
event CancelOffer(uint256 indexed id);
event AcceptOffer(uint256 indexed id, address indexed user, uint256 price);
event NewTreasuryAddress(address _treasuryAddress);
event NFTBlackListUpdate(address nft, bool state);
event NFTAccrualListUpdate(address nft, bool state);
event DealTokensWhiteListUpdate(address token, bool whiteListed);
event NewUserFee(address user, uint256 fee);
event SetRoyalty(
address nftAddress,
address royaltyReceiver,
uint32 rate,
bool enable
);
constructor(
address _treasuryAddress,
ISwapFeeRewardWithRB _feeRewardRB
) {
//NFT-01
require(_treasuryAddress != address(0), "Address cant be zero");
treasuryAddress = _treasuryAddress;
feeRewardRB = _feeRewardRB;
feeRewardRBIsEnabled = false;
// take id(0) as placeholder
offers.push(
Offer({
tokenId: 0,
price: 0,
nft: IERC721(address(0)),
dealToken: IERC20(address(0)),
user: address(0),
acceptUser: address(0),
status: OfferStatus.Cancelled,
side: Side.Buy
})
);
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function enableRBFeeReward() public onlyOwner {
feeRewardRBIsEnabled = true;
}
function disableRBFeeReward() public onlyOwner {
feeRewardRBIsEnabled = false;
}
function enablePlacementReward() public onlyOwner {
placementRewardEnabled = true;
}
function disablePlacementReward() public onlyOwner {
placementRewardEnabled = false;
}
function setTreasuryAddress(address _treasuryAddress) public onlyOwner {
//NFT-01
require(_treasuryAddress != address(0), "Address cant be zero");
treasuryAddress = _treasuryAddress;
emit NewTreasuryAddress(_treasuryAddress);
}
function setRewardDistributionSeller(uint256 _rewardDistributionSeller)
public
onlyOwner
{
require(
_rewardDistributionSeller <= 100,
"Incorrect value Must be equal to or greater than 100"
);
rewardDistributionSeller = _rewardDistributionSeller;
}
function setRoyalty(
address nftAddress,
address royaltyReceiver,
uint32 rate,
bool enable
) public onlyOwner {
require(nftAddress != address(0), "Address cant be zero");
require(royaltyReceiver != address(0), "Address cant be zero");
require(rate < 10000, "Rate must be less than 10000");
royalty[nftAddress].receiver = royaltyReceiver;
royalty[nftAddress].rate = rate;
royalty[nftAddress].enable = enable;
emit SetRoyalty(nftAddress, royaltyReceiver, rate, enable);
}
function addBlackListNFT(address[] calldata nfts) public onlyOwner {
for (uint256 i = 0; i < nfts.length; i++) {
nftBlacklist[nfts[i]] = true;
emit NFTBlackListUpdate(nfts[i], true);
}
}
function delBlackListNFT(address[] calldata nfts) public onlyOwner {
for (uint256 i = 0; i < nfts.length; i++) {
delete nftBlacklist[nfts[i]];
emit NFTBlackListUpdate(nfts[i], false);
}
}
function addWhiteListDealTokens(address[] calldata _tokens)
public
onlyOwner
{
for (uint256 i = 0; i < _tokens.length; i++) {
require(_tokens[i] != address(0), "Address cant be 0");
dealTokensWhitelist[_tokens[i]] = true;
emit DealTokensWhiteListUpdate(_tokens[i], true);
}
}
function delWhiteListDealTokens(address[] calldata _tokens)
public
onlyOwner
{
for (uint256 i = 0; i < _tokens.length; i++) {
delete dealTokensWhitelist[_tokens[i]];
emit DealTokensWhiteListUpdate(_tokens[i], false);
}
}
function addNftForAccrualRB(address _nft) public onlyOwner {
require(_nft != address(0), "Address cant be zero");
nftForAccrualRB[_nft] = true;
emit NFTAccrualListUpdate(_nft, true);
}
function delNftForAccrualRB(address _nft) public onlyOwner {
require(_nft != address(0), "Address cant be zero");
delete nftForAccrualRB[_nft];
emit NFTAccrualListUpdate(_nft, false);
}
function setUserFee(address user, uint256 fee) public onlyOwner {
userFee[user] = fee;
emit NewUserFee(user, fee);
}
function setDefaultFee(uint256 _newFee) public onlyOwner {
require(
_newFee <= MAX_DEFAULT_FEE,
"New fee must be less than or equal to max fee"
);
defaultFee = _newFee;
}
function SetMaxUserTokenOnSellToReward(uint8 newCount) public onlyOwner {
maxUserTokenOnSellToReward = newCount;
}
function setSmartChefMarket(ISmartChefMarket _smartChefMarket)
public
onlyOwner
{
require(address(_smartChefMarket) != address(0), "Address cant be 0");
smartChefMarket = _smartChefMarket;
}
function setFeeRewardRB(ISwapFeeRewardWithRB _feeRewardRB)
public
onlyOwner
{
require(address(_feeRewardRB) != address(0), "Address cant be 0");
feeRewardRB = _feeRewardRB;
}
// user functions
function offer(
Side side,
address dealToken,
IERC721 nft,
uint256 tokenId,
uint256 price
)
public
nonReentrant
whenNotPaused
_nftAllowed(nft)
_validDealToken(dealToken)
notContract
{
if (side == Side.Buy) {
_offerBuy(nft, tokenId, price, dealToken);
} else if (side == Side.Sell) {
_offerSell(nft, tokenId, price, dealToken);
} else {
revert("Not supported");
}
}
function accept(uint256 id)
public
nonReentrant
_offerExists(id)
_offerOpen(id)
_notBlackListed(id)
whenNotPaused
notContract
{
if (offers[id].side == Side.Buy) {
_acceptBuy(id);
} else {
_acceptSell(id);
}
}
function cancel(uint256 id)
public
nonReentrant
_offerExists(id)
_offerOpen(id)
_offerOwner(id)
whenNotPaused
{
if (offers[id].side == Side.Buy) {
_cancelBuy(id);
} else {
_cancelSell(id);
}
}
function multiCancel(uint256[] calldata ids) public notContract {
for (uint256 i = 0; i < ids.length; i++) {
cancel(ids[i]);
}
}
//increase: true - increase token to accrue rewards; false - decrease token from
function placementRewardQualifier(
bool increase,
address user,
address nftToken
) internal {
//Check if nft token in nftForAccrualRB list and accrue reward enable
if (!nftForAccrualRB[nftToken] || !placementRewardEnabled) return;
if (increase) {
tokensCount[user]++;
} else {
tokensCount[user] = tokensCount[user] > 0
? tokensCount[user] - 1
: 0;
}
if (tokensCount[user] > maxUserTokenOnSellToReward) return;
uint256 stakedAmount = tokensCount[user] >= maxUserTokenOnSellToReward
? maxUserTokenOnSellToReward
: tokensCount[user];
smartChefMarket.updateStakedTokens(user, stakedAmount);
}
function _offerSell(
IERC721 nft,
uint256 tokenId,
uint256 price,
address dealToken
) internal {
require(msg.value == 0, "Seller should not pay");
require(price > 0, "price > 0");
offers.push(
Offer({
tokenId: tokenId,
price: price,
dealToken: IERC20(dealToken),
nft: nft,
user: msg.sender,
acceptUser: address(0),
status: OfferStatus.Open,
side: Side.Sell
})
);
uint256 id = offers.length - 1;
emit NewOffer(
msg.sender,
nft,
tokenId,
dealToken,
price,
Side.Sell,
id
);
require(getTokenOwner(id) == msg.sender, "sender should own the token");
require(isTokenApproved(id, msg.sender), "token is not approved");
if (tokenSellOffers[nft][tokenId] > 0) {
_closeSellOfferFor(nft, tokenId);
} else {
placementRewardQualifier(true, msg.sender, address(nft));
}
tokenSellOffers[nft][tokenId] = id;
}
function _offerBuy(
IERC721 nft,
uint256 tokenId,
uint256 price,
address dealToken
) internal {
IERC20(dealToken).safeTransferFrom(msg.sender, address(this), price);
require(price > 0, "buyer should pay");
offers.push(
Offer({
tokenId: tokenId,
price: price,
dealToken: IERC20(dealToken),
nft: nft,
user: msg.sender,
acceptUser: address(0),
status: OfferStatus.Open,
side: Side.Buy
})
);
uint256 id = offers.length - 1;
emit NewOffer(msg.sender, nft, tokenId, dealToken, price, Side.Buy, id);
_closeUserBuyOffer(userBuyOffers[msg.sender][nft][tokenId]);
userBuyOffers[msg.sender][nft][tokenId] = id;
}
function _acceptBuy(uint256 id) internal {
// caller is seller
Offer storage _offer = offers[id];
require(msg.value == 0, "seller should not pay");
require(getTokenOwner(id) == msg.sender, "only owner can call");
require(isTokenApproved(id, msg.sender), "token is not approved");
_offer.status = OfferStatus.Accepted;
_offer.acceptUser = msg.sender;
_offer.nft.safeTransferFrom(msg.sender, _offer.user, _offer.tokenId);
_distributePayment(_offer);
emit AcceptOffer(id, msg.sender, _offer.price);
_unlinkBuyOffer(_offer);
if (tokenSellOffers[_offer.nft][_offer.tokenId] > 0) {
_closeSellOfferFor(_offer.nft, _offer.tokenId);
//NFT-03
placementRewardQualifier(false, msg.sender, address(_offer.nft));
}
}
function _acceptSell(uint256 id) internal {
// caller is buyer
Offer storage _offer = offers[id];
if (
getTokenOwner(id) != _offer.user ||
isTokenApproved(id, _offer.user) == false
) {
_cancelSell(id);
return;
}
_offer.status = OfferStatus.Accepted;
_offer.acceptUser = msg.sender;
_unlinkSellOffer(_offer);
_offer.dealToken.safeTransferFrom(msg.sender, address(this), _offer.price);
_distributePayment(_offer);
_offer.nft.safeTransferFrom(_offer.user, msg.sender, _offer.tokenId);
emit AcceptOffer(id, msg.sender, _offer.price);
}
function _cancelSell(uint256 id) internal {
Offer storage _offer = offers[id];
require(_offer.status == OfferStatus.Open, "Offer was cancelled");
_offer.status = OfferStatus.Cancelled;
emit CancelOffer(id);
_unlinkSellOffer(_offer);
}
function _cancelBuy(uint256 id) internal {
Offer storage _offer = offers[id];
require(_offer.status == OfferStatus.Open, "Offer was cancelled");
_offer.status = OfferStatus.Cancelled;
_transfer(msg.sender, _offer.price, _offer.dealToken);
emit CancelOffer(id);
_unlinkBuyOffer(_offer);
}
// modifiers
modifier _validDealToken(address _token) {
require(dealTokensWhitelist[_token], "Deal token not available");
_;
}
modifier _offerExists(uint256 id) {
require(id > 0 && id < offers.length, "offer does not exist");
_;
}
modifier _offerOpen(uint256 id) {
require(offers[id].status == OfferStatus.Open, "offer should be open");
_;
}
modifier _offerOwner(uint256 id) {
require(offers[id].user == msg.sender, "call should own the offer");
_;
}
modifier _notBlackListed(uint256 id) {
Offer storage _offer = offers[id];
require(!nftBlacklist[address(_offer.nft)], "NFT in black list");
_;
}
modifier _nftAllowed(IERC721 nft) {
require(!nftBlacklist[address(nft)], "NFT in black list");
_;
}
modifier notContract() {
require(!_isContract(msg.sender), "Contract not allowed");
require(msg.sender == tx.origin, "Proxy contract not allowed");
_;
}
// internal functions
function _transfer(
address to,
uint256 amount,
IERC20 _dealToken
) internal {
require(amount > 0 && to != address(0), "Wrong amount or dest on transfer");
_dealToken.safeTransfer(to, amount);
}
function _distributePayment(Offer memory _offer) internal {
(address seller, address buyer) = _offer.side == Side.Sell
? (_offer.user, _offer.acceptUser)
: (_offer.acceptUser, _offer.user);
uint256 feeRate = userFee[seller] == 0 ? defaultFee : userFee[seller];
uint256 fee = (_offer.price * feeRate) / 10000;
uint256 royaltyFee = 0;
if (royalty[address(_offer.nft)].enable) {
royaltyFee =
(_offer.price * royalty[address(_offer.nft)].rate) /
10000;
_transfer(
royalty[address(_offer.nft)].receiver,
royaltyFee,
_offer.dealToken
);
}
_transfer(treasuryAddress, fee, _offer.dealToken);
_transfer(seller, _offer.price - fee - royaltyFee, _offer.dealToken);
if (feeRewardRBIsEnabled && nftForAccrualRB[address(_offer.nft)]) {
feeRewardRB.accrueRBFromMarket(
seller,
address(_offer.dealToken),
(fee * rewardDistributionSeller) / 100
);
feeRewardRB.accrueRBFromMarket(
buyer,
address(_offer.dealToken),
(fee * (100 - rewardDistributionSeller)) / 100
);
}
}
function _closeSellOfferFor(IERC721 nft, uint256 tokenId) internal {
uint256 id = tokenSellOffers[nft][tokenId];
if (id == 0) return;
// closes old open sell offer
Offer storage _offer = offers[id];
_offer.status = OfferStatus.Cancelled;
tokenSellOffers[_offer.nft][_offer.tokenId] = 0;
emit CancelOffer(id);
}
function _closeUserBuyOffer(uint256 id) internal {
Offer storage _offer = offers[id];
if (
id > 0 &&
_offer.status == OfferStatus.Open &&
_offer.side == Side.Buy
) {
_offer.status = OfferStatus.Cancelled;
_transfer(_offer.user, _offer.price, _offer.dealToken);
_unlinkBuyOffer(_offer);
emit CancelOffer(id);
}
}
function _unlinkBuyOffer(Offer storage o) internal {
userBuyOffers[o.user][o.nft][o.tokenId] = 0;
}
function _unlinkSellOffer(Offer storage o) internal {
placementRewardQualifier(false, o.user, address(o.nft));
tokenSellOffers[o.nft][o.tokenId] = 0;
}
// helpers
function isValidSell(uint256 id) public view returns (bool) {
if (id >= offers.length) {
return false;
}
Offer storage _offer = offers[id];
// try to not throw exception
return
_offer.status == OfferStatus.Open &&
_offer.side == Side.Sell &&
isTokenApproved(id, _offer.user) &&
(_offer.nft.ownerOf(_offer.tokenId) == _offer.user);
}
function isTokenApproved(uint256 id, address owner)
public
view
returns (bool)
{
Offer storage _offer = offers[id];
return
_offer.nft.getApproved(_offer.tokenId) == address(this) ||
_offer.nft.isApprovedForAll(owner, address(this));
}
function getTokenOwner(uint256 id) public view returns (address) {
Offer storage _offer = offers[id];
return _offer.nft.ownerOf(_offer.tokenId);
}
function _isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
}
| max count sell offers of nftForAccrualRB on which Rb accrual
| uint8 public maxUserTokenOnSellToReward = 3; | 5,521,047 | [
1,
1896,
1056,
357,
80,
28641,
434,
290,
1222,
1290,
8973,
86,
1462,
19437,
603,
1492,
31800,
4078,
86,
1462,
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
] | [
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,
0
] | [
1,
565,
2254,
28,
1071,
943,
1299,
1345,
1398,
55,
1165,
774,
17631,
1060,
273,
890,
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
] |
./partial_match/3/0x65B29b471f69400244Ffee30914745c88883810d/sources/pool.sol | * @dev settle call option contract/ ignore 0 supply option ignore 0 strikePrice option | function _settleOption(Option option, uint etherPrice) internal override {
if (option.totalSupply() == 0) {
return;
}
if (option.strikePrice() == 0) {
return;
}
uint256 strikePrice = option.strikePrice();
.div(strikePrice);
.mul(totalOptionSold)
}
| 5,237,092 | [
1,
542,
5929,
745,
1456,
6835,
19,
2305,
374,
14467,
1456,
2305,
374,
609,
2547,
5147,
1456,
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,
389,
542,
5929,
1895,
12,
1895,
1456,
16,
2254,
225,
2437,
5147,
13,
2713,
3849,
288,
203,
3639,
309,
261,
3482,
18,
4963,
3088,
1283,
1435,
422,
374,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
3482,
18,
701,
2547,
5147,
1435,
422,
374,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
203,
3639,
2254,
5034,
609,
2547,
5147,
273,
1456,
18,
701,
2547,
5147,
5621,
203,
4766,
565,
263,
2892,
12,
701,
2547,
5147,
1769,
203,
203,
2398,
203,
4766,
565,
263,
16411,
12,
4963,
1895,
55,
1673,
13,
203,
203,
203,
3639,
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
] |
./partial_match/8453/0xBcFF559E85791cEDcF2541d1f20c9471801D1f02/sources/contracts/EisenDiamond.sol | Find facet for function that is called and execute the function if a facet is found and return any value. solhint-disable-next-line no-complex-fallback get diamond storage solhint-disable-next-line no-inline-assembly Execute external function from facet using delegatecall and return any value. solhint-disable-next-line no-inline-assembly copy function selector and any arguments execute function call using the facet get any return value return any return value or error back to the caller 0xa0d0feeb == function selector of flashloan ["flashloan(address,address[],uint256[],uint256[],bytes)"] flashloan | fallback() external payable {
LibDiamond.DiamondStorage storage ds;
bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
if (facet == address(0)) {
revert LibDiamond.DiamondError(LibDiamond.FUNCTION_DOES_NOT_EXIST);
}
bytes4 selector = bytes4(msg.sig);
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
if eq(selector, 0xa0d0feeb) {
return(0, returndatasize())
}
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
| 16,713,644 | [
1,
3125,
11082,
364,
445,
716,
353,
2566,
471,
1836,
326,
445,
309,
279,
11082,
353,
1392,
471,
327,
1281,
460,
18,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
14259,
17,
16471,
336,
4314,
301,
1434,
2502,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
10047,
17,
28050,
7903,
3903,
445,
628,
11082,
1450,
7152,
1991,
471,
327,
1281,
460,
18,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
10047,
17,
28050,
1610,
445,
3451,
471,
1281,
1775,
1836,
445,
745,
1450,
326,
11082,
336,
1281,
327,
460,
327,
1281,
327,
460,
578,
555,
1473,
358,
326,
4894,
374,
6995,
20,
72,
20,
21386,
70,
422,
445,
3451,
434,
9563,
383,
304,
8247,
13440,
383,
304,
12,
2867,
16,
2867,
63,
6487,
11890,
5034,
63,
6487,
11890,
5034,
63,
6487,
3890,
2225,
65,
9563,
383,
304,
2,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [
1,
565,
5922,
1435,
3903,
8843,
429,
288,
203,
3639,
10560,
14521,
301,
1434,
18,
14521,
301,
1434,
3245,
2502,
3780,
31,
203,
3639,
1731,
1578,
1754,
273,
10560,
14521,
301,
1434,
18,
2565,
2192,
673,
40,
67,
19009,
67,
15258,
31,
203,
203,
3639,
19931,
288,
203,
5411,
3780,
18,
14194,
519,
1754,
203,
3639,
289,
203,
203,
203,
3639,
309,
261,
21568,
422,
1758,
12,
20,
3719,
288,
203,
5411,
15226,
10560,
14521,
301,
1434,
18,
14521,
301,
1434,
668,
12,
5664,
14521,
301,
1434,
18,
7788,
67,
3191,
3991,
67,
4400,
67,
11838,
1769,
203,
3639,
289,
203,
203,
3639,
1731,
24,
3451,
273,
1731,
24,
12,
3576,
18,
7340,
1769,
203,
203,
3639,
19931,
288,
203,
5411,
745,
892,
3530,
12,
20,
16,
374,
16,
745,
13178,
554,
10756,
203,
5411,
2231,
563,
519,
7152,
1991,
12,
31604,
9334,
11082,
16,
374,
16,
745,
13178,
554,
9334,
374,
16,
374,
13,
203,
5411,
327,
892,
3530,
12,
20,
16,
374,
16,
327,
13178,
554,
10756,
203,
5411,
1620,
563,
203,
5411,
648,
374,
288,
203,
7734,
309,
7555,
12,
9663,
16,
374,
6995,
20,
72,
20,
21386,
70,
13,
288,
203,
10792,
327,
12,
20,
16,
327,
13178,
554,
10756,
203,
7734,
289,
203,
203,
7734,
15226,
12,
20,
16,
327,
13178,
554,
10756,
203,
5411,
289,
203,
5411,
805,
288,
203,
7734,
327,
12,
20,
16,
327,
13178,
554,
10756,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x94D365E8E8c73Da739879D6F322A3921eb66CFb0/sources/FixedSwap.sol | * Modifier to make a function callable only when the contract has Atomic Swaps not available./ | modifier isSalePreStarted() {
require(isPreStart());
_;
}
| 3,465,391 | [
1,
9829,
358,
1221,
279,
445,
4140,
1338,
1347,
326,
6835,
711,
11553,
5434,
6679,
486,
2319,
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
] | [
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,
0,
0
] | [
1,
565,
9606,
11604,
5349,
1386,
9217,
1435,
288,
203,
3639,
2583,
12,
291,
1386,
1685,
10663,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xdc888B8c76eF26852B6f6c0008D6E2f29A96Cb50/sources/contracts-verify/KIBTAggregator.sol | * @return Maximum absolute value change of the answer between two consecutive rounds./ | function getVolatilityThreshold() external view returns (uint256) {
return _volatilityThreshold;
}
| 9,350,623 | [
1,
2463,
18848,
4967,
460,
2549,
434,
326,
5803,
3086,
2795,
18221,
21196,
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,
565,
445,
11031,
355,
30139,
7614,
1435,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
15416,
30139,
7614,
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
] |
pragma solidity >=0.4.21 <0.7.0;
import "./DateTime.sol";
contract Vote {
string public voteName;
uint256 public voteEndDate;
address public voteDeployer; // deployer decide who can vote and stock of each Voter
uint public totalCandidateNumber = 0; // how many people are in the cadidate map
uint public maxNominatedNum; // how many people can be nominated
DateTime dateTime;
// vote type should be straight voting or cumulative voting
// 1-> straight voting
// 2-> cumulative voting
uint public voteType = 1;
// should decide the total stock
// should decide the threshold of the max stock of a Voter
// the stock cannot be changed after the deployer confirms
uint public totalShareNum;
uint public maxShareNum;
uint public currentTotalShareNum = 0;
// deployer should confirm when finish deploying the stock
bool comfirm = false;
mapping(uint => Candidate) public candidates;
mapping(address => Voter) public voters;
mapping(uint => ContractDate) public contractDates;
struct Candidate {
uint candidateId;
string candidateName;
string candidatePhoto;
string candidateInfo;
uint candidateTotalVote;
}
struct OneVote {
uint candidateId;
uint voteNum;
}
struct Voter{
uint voteChangeNum; // how many times I have changed my voted
uint stock; // is share the voter has
uint totalVoteNum; // how many votes do I have
uint voteUsed; // how many votes do I use
uint numOfPeopleNominated; // how many people do I nominate
mapping (uint => OneVote) myVote; // record for all the nominator I voted
bool hasVoted;
}
struct ContractDate {
uint year;
uint month;
uint day;
}
event allocateShareEvent(
address voter,
uint stock
);
event newVoteRecord(
uint candidateId,
uint voteNum
);
event changeVoteRecord(
uint candidateId,
uint voteNum
);
event lookForInfo(
uint candidateId,
uint inputId
);
event addCandidate(
uint candidateId,
string candidateName,
string candidatePhoto,
string candidateInfo,
uint candidateTotalVote
);
event vote(
uint voteName,
uint voteTime,
bool hasVoted
);
event lookUpMyVote(
address myAddr,
uint[] recordID,
uint[] candidateID,
uint[] voteNum
);
event errorMessage(
string errMsg
);
// voting process
// 1. define the candidate, candidate modifying period, voting period, max Nominating Num, total stock, max stock, and voting type
// 2. deployer allocate the share of each voters, voter without any share cannot vote
// 3. if it's straight voting, then every valid voter can have one vote per share for each nominator
// e.g. The voting have 10 candidate, the voting need to select 3 of them to be in board of directors.
// Voter Ben has 20 stock thus, he can nominate 3 people, and all these three will have 20 votes
// 4. if it's cumulative voting, then every voter can have voteNum = stock * maxNominatedNum, and voter can freely distrubute his votes
constructor(uint256 _maxNominatedNum, uint256 _totalShareNum, uint256 _maxShareNum, uint _voteType) public {
voteName = "block chain vote app";
maxNominatedNum = _maxNominatedNum;
totalShareNum = _totalShareNum;
maxShareNum = _maxShareNum;
voteType = _voteType;
voteDeployer = msg.sender;
dateTime = new DateTime();
contractDateSetting(0, dateTime.getYear(now), dateTime.getMonth(now), dateTime.getDay(now));
}
// this func create a new candidate, only deployer can call this func
// name and info of candidate must be not null
// default candidate photo url is: https://en.wikipedia.org/wiki/Anonymous_(group)#/media/File:Anonymous_emblem.svg
// future direction: the current time is the value returned by JS func:
// 1.let date = (new Date()).getTime();
// 2.let currentDate = date / 1000;
// current time should be within the creating new cadidate period
function createNewCandidate(string memory _cadidateName, string memory _candidatePhoto,
string memory _cadidateInfo) public {
if(msg.sender != voteDeployer) {
emit errorMessage("You can't create new cadidate. Only deployer can do this.");
return;
}
require(msg.sender == voteDeployer, "You can't create new cadidate. Only deployer can do this.");
require(bytes(_cadidateName).length > 0, "candidate name is required");
require(bytes(_cadidateInfo).length > 0, "candidate info is required");
totalCandidateNumber++;
string memory photo = "https://en.wikipedia.org/wiki/Anonymous_(group)#/media/File:Anonymous_emblem.svg";
if(bytes(_candidatePhoto).length > 0){photo = _candidatePhoto;}
candidates[totalCandidateNumber] = Candidate(totalCandidateNumber,_cadidateName,photo,_cadidateInfo,0);
emit addCandidate(totalCandidateNumber,_cadidateName,photo,_cadidateInfo,0);
}
// this func allocate the share to one shareholder, only deployer can call this func
// the share of one voter should not greater than max share amount that a voter can hold
// the currentTotalShareNum + _stockNum should not greater than total share available
function allocateShare(address _voterAddr, uint _shareNum) public {
if(msg.sender != voteDeployer) {
emit errorMessage("You can't deploy share. Only deployer can do this.");
return;
}
require(msg.sender == voteDeployer, "You can't deploy share. Only deployer can do this.");
if(_shareNum > maxShareNum){
emit errorMessage("You can't deploy this share because it is over max share per person.");
return;
}
require(_shareNum <= maxShareNum, "You can't deploy this stock number for this voter.");
if((currentTotalShareNum + _shareNum) > totalShareNum) {
emit errorMessage("You can't deploy more share, current share is over total share limit.");
return;
}
require((currentTotalShareNum + _shareNum) <= totalShareNum,
"You can't deploy more share, current share is over total share limit.");
//add to currentTotalShareNum
currentTotalShareNum = currentTotalShareNum + _shareNum;
Voter memory _voter = voters[_voterAddr];
_voter.stock = _shareNum;
_voter.totalVoteNum = _shareNum * maxNominatedNum;
voters[_voterAddr] = _voter;
emit allocateShareEvent(_voterAddr, _shareNum);
}
// this func let voter vote for a candidate
// _candidateId: the candidate you want to vote
// _voteNum: the number of votes
// _currentDate: future direction, the current time is the value returned by JS func:
// 1.let date = (new Date()).getTime();
// 2.let currentDate = date / 1000;
// basic logic
// current time should be within the voting period
// if voter has not voted before, then he can vote
// if numOfPeopleNominated < maxNominatedNum then he can voteForCandidate
// if voter has stock then he can voteForCandidate
// if voter still has votes left he can vote
function voteForCandidate(uint _candidateId, uint _voteNum) public {
if(_candidateId < 0 || _candidateId > totalCandidateNumber) {
emit errorMessage("Invalid Candidate Id.");
return;
}
require(_candidateId > 0 && _candidateId <= totalCandidateNumber, "Invalid Candidate Id.");
if(voters[msg.sender].stock <= 0) {
emit errorMessage("You don't have any share. You can't vote.");
return;
}
require(voters[msg.sender].stock > 0, "You don't have any share. You can't vote.");
if(voters[msg.sender].numOfPeopleNominated > maxNominatedNum) {
emit errorMessage("You can't vote for any more nominator. You can't vote.");
return;
}
require(voters[msg.sender].numOfPeopleNominated <= maxNominatedNum,
"You can't vote for any more nominator. You can't vote.");
// get the last voting info
Voter memory _voter = voters[msg.sender];
// still has votes left?
if(voteType == 1){
if(_voter.voteUsed + voters[msg.sender].stock > _voter.totalVoteNum) {
emit errorMessage("You don't have enough votes.");
return;
}
require(_voter.voteUsed + voters[msg.sender].stock <= _voter.totalVoteNum,
"You don't have enough votes.");
} else {
if(_voter.voteUsed + _voteNum > _voter.totalVoteNum) {
emit errorMessage("You don't have enough votes.");
return;
}
require(_voter.voteUsed + _voteNum <= _voter.totalVoteNum, "You don't have enough votes.");
}
// check wether you have voted for this candidates or not
bool votedForCandidate = false;
for(uint i = 0; i <= voters[msg.sender].numOfPeopleNominated; i++){
//emit lookForInfo(voters[msg.sender].myVote[i].candidateId, _candidateId);
if(voters[msg.sender].myVote[i].candidateId == _candidateId){
votedForCandidate = true;
}
}
if(votedForCandidate) {
emit errorMessage("You have voted for this candidate.");
return;
}
require(!votedForCandidate,
"You have voted for this candidate.");
// then lets input the new voting info
voters[msg.sender].numOfPeopleNominated++;
voters[msg.sender].hasVoted = true;
uint currentVoteStock;
if(voteType == 1) {
currentVoteStock = voters[msg.sender].stock;
} else {
currentVoteStock = _voteNum;
}
OneVote memory myNewVote = OneVote(_candidateId, currentVoteStock);
voters[msg.sender].myVote[_voter.numOfPeopleNominated] = myNewVote;
voters[msg.sender].voteUsed += currentVoteStock;
Candidate memory _cadidate = candidates[_candidateId];
_cadidate.candidateTotalVote += currentVoteStock;
candidates[_candidateId] = _cadidate;
emit newVoteRecord(_candidateId, currentVoteStock);
}
// this func can let you look up all the vote records
function lookUpVoteRecord() public{
uint num_p = voters[msg.sender].numOfPeopleNominated;
if(num_p == 0) {
emit errorMessage("You have not voted for any candidates yet, no vote record.");
return;
}
uint256[] memory recordID = new uint256[](num_p);
uint256[] memory candidateID = new uint256[](num_p);
uint256[] memory voteNum = new uint256[](num_p);
for(uint _recordId = 0;_recordId < num_p;_recordId++){
recordID[_recordId] = _recordId;
candidateID[_recordId] = voters[msg.sender].myVote[_recordId].candidateId;
voteNum[_recordId] = voters[msg.sender].myVote[_recordId].voteNum;
}
emit lookUpMyVote(msg.sender,recordID,candidateID,voteNum);
}
// this func change the EXISTING record in myVote struct.
//_candidateId: the new candidate you want to vote
//_newVote: num of votes
//_voteInfoNum: the voting record you want to edit
// _currentDate: future direction. For now it will be a constant input
//basic logic
// it will first retrieve the vote you want to modify
// then it will deduct the votes from the previous candidate you vote
// after that it will add the vote to the new candidate you want to vote
// this func won't change the numOfPeopleNominated
function changeMyVote(uint _candidateId, uint _newVote, uint _voteInfoNum) public {
if(_candidateId < 0 || _candidateId > totalCandidateNumber) {
emit errorMessage("Invalid Candidate Id.");
return;
}
require(_candidateId > 0 && _candidateId <= totalCandidateNumber, "Invalid Candidate Id.");
if(voters[msg.sender].hasVoted == false) {
emit errorMessage("You have not voted any candidates.");
return;
}
if(voters[msg.sender].voteChangeNum >= 3) {
emit errorMessage("You have access your max vote modifying times(3 times).");
return;
}
require(voters[msg.sender].hasVoted == true && voters[msg.sender].voteChangeNum < 3,
"You have access your max vote modifying times(3 times).");
if(voters[msg.sender].myVote[_voteInfoNum - 1].voteNum <= 0) {
emit errorMessage("Voting info ID is wrong, you haven't voted for this candidate.");
return;
}
require(voters[msg.sender].myVote[_voteInfoNum - 1].voteNum > 0,
"Voting info ID is wrong, you haven't voted for this candidate.");
// get the last voting info
Voter memory _voter = voters[msg.sender];
OneVote memory _voteToModify = voters[msg.sender].myVote[_voteInfoNum - 1];
// emit lookForInfo(_voteToModify.candidateId, _voteToModify.voteNum);
// total voteUsed checking
if(voteType == 2) {
uint myLastVoteNum = _voteToModify.voteNum;
if(_voter.voteUsed - myLastVoteNum + _newVote > _voter.totalVoteNum) {
emit errorMessage("You don't have enough votes.");
return;
}
require(_voter.voteUsed - myLastVoteNum + _newVote <= _voter.totalVoteNum, "You don't have enough votes.");
} else {
// if you have vote for this candidate then don't vote, cuz in type 1 every candidate can only be voted once
bool votedForCandidate = false;
for(uint i = 0; i <= voters[msg.sender].numOfPeopleNominated; i++){
//emit lookForInfo(voters[msg.sender].myVote[i].candidateId,_candidateId);
if(voters[msg.sender].myVote[i].candidateId == _candidateId && voters[msg.sender].myVote[i].voteNum > 0) {
votedForCandidate = true;
}
}
if(votedForCandidate) {
emit errorMessage("You have voted for this candidate.");
return;
}
require(!votedForCandidate, "You have voted for this candidate.");
}
// now start to modify
voters[msg.sender].voteChangeNum++;
// last candidate I vote
Candidate memory _lastVoteCandidate = candidates[_voteToModify.candidateId];
// retrieve the voteNumUsed and the candidate voteNum
_lastVoteCandidate.candidateTotalVote -= _voteToModify.voteNum;
candidates[_voteToModify.candidateId] = _lastVoteCandidate;
voters[msg.sender].voteUsed -= _voteToModify.voteNum;
// now input the new vote info
uint currentVoteNum;
if(voteType == 1) {
currentVoteNum = voters[msg.sender].stock;
} else {
currentVoteNum = _newVote;
}
OneVote memory myNewVote = OneVote(_candidateId, currentVoteNum);
voters[msg.sender].voteUsed += currentVoteNum;
voters[msg.sender].myVote[_voteInfoNum - 1] = myNewVote;
Candidate memory _cadidate = candidates[_candidateId];
_cadidate.candidateTotalVote += currentVoteNum;
candidates[_candidateId] = _cadidate;
emit changeVoteRecord(_candidateId, currentVoteNum);
}
function contractDateSetting(uint _index, uint _year, uint _month, uint _day) public {
if(_index == 0) {
for(uint i = 1; i <= 4; i++){
contractDates[i] = ContractDate(_year, _month, _day);
}
} else {
ContractDate memory _contractDate = contractDates[_index];
_contractDate.year = _year;
_contractDate.month = _month;
_contractDate.day = _day;
contractDates[_index] = _contractDate;
}
emit errorMessage("Date Change Finished!");
}
function changeVoteType() public {
if (voteType == 1) {
voteType = 2;
} else {
voteType = 1;
}
emit errorMessage("Vote Type Change Finished!");
}
} | get the last voting info | Voter memory _voter = voters[msg.sender];
| 6,350,604 | [
1,
588,
326,
1142,
331,
17128,
1123,
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,
776,
20005,
3778,
389,
90,
20005,
273,
331,
352,
414,
63,
3576,
18,
15330,
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
] |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
| TODO: should increase instead | function approve_779(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,454,492 | [
1,
6241,
30,
1410,
10929,
3560,
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,
225,
445,
6617,
537,
67,
4700,
29,
12,
2867,
17571,
264,
16,
2254,
460,
13,
1071,
1135,
261,
6430,
1529,
13,
288,
203,
565,
389,
12908,
4524,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
460,
31,
203,
565,
3626,
1716,
685,
1125,
12,
1234,
18,
15330,
16,
17571,
264,
16,
460,
11272,
203,
565,
327,
638,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x95790e3bec5640977A4f70f02ebC1d3E6013Fd5A/sources/xAAVEProxy.sol | * @dev Returns the timestamp that the proposed admin can be changed/confirmed/ | function proposedNewAdminTimestamp() public view returns (uint256 timestamp) {
timestamp = readIntAtPosition(PROPOSED_NEW_ADMIN_TIMESTAMP);
}
| 4,034,647 | [
1,
1356,
326,
2858,
716,
326,
20084,
3981,
848,
506,
3550,
19,
21606,
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,
20084,
1908,
4446,
4921,
1435,
1071,
1476,
1135,
261,
11890,
5034,
2858,
13,
288,
203,
3639,
2858,
273,
13731,
861,
2555,
12,
3373,
2419,
18204,
67,
12917,
67,
15468,
67,
17201,
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
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
//import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Math} from "@openzeppelin/contracts/math/Math.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {CDP} from "./libraries/alchemist/CDP.sol";
import {FixedPointMath} from "./libraries/FixedPointMath.sol";
import {ITransmuter} from "./interfaces/ITransmuter.sol";
import {IMintableERC20} from "./interfaces/IMintableERC20.sol";
import {IChainlink} from "./interfaces/IChainlink.sol";
import {IVaultAdapter} from "./interfaces/IVaultAdapter.sol";
import {Vault} from "./libraries/alchemist/Vault.sol";
import {IWETH9} from "./interfaces/IWETH9.sol";
import {AlEth} from "./AlEth.sol";
// ERC20,removing ERC20 from the alchemist
// ___ __ __ _ ___ __ _
// / _ | / / ____ / / ___ __ _ (_) __ __ / _ \ ____ ___ ___ ___ ___ / /_ ___ (_)
// / __ | / / / __/ / _ \/ -_) / ' \ / / \ \ / / ___/ / __// -_) (_-</ -_) / _ \/ __/ (_-< _
// /_/ |_|/_/ \__/ /_//_/\__/ /_/_/_//_/ /_\_\ /_/ /_/ \__/ /___/\__/ /_//_/\__/ /___/(_)
//
// ___ __ ______ __ __ _______ .___ ___. __ _______..___________.
// / \ | | / || | | | | ____|| \/ | | | / || |
// / ^ \ | | | ,----'| |__| | | |__ | \ / | | | | (----``---| |----`
// / /_\ \ | | | | | __ | | __| | |\/| | | | \ \ | |
// / _____ \ | `----.| `----.| | | | | |____ | | | | | | .----) | | |
// /__/ \__\ |_______| \______||__| |__| |_______||__| |__| |__| |_______/ |__|
contract AlchemistEth is ReentrancyGuard {
using CDP for CDP.Data;
using FixedPointMath for FixedPointMath.FixedDecimal;
using Vault for Vault.Data;
using Vault for Vault.List;
using SafeERC20 for IMintableERC20;
using SafeMath for uint256;
using Address for address;
address public constant ZERO_ADDRESS = address(0);
/// @dev Resolution for all fixed point numeric parameters which represent percents. The resolution allows for a
/// granularity of 0.01% increments.
uint256 public constant PERCENT_RESOLUTION = 10000;
/// @dev The minimum value that the collateralization limit can be set to by the governance. This is a safety rail
/// to prevent the collateralization from being set to a value which breaks the system.
///
/// This value is equal to 100%.
///
/// IMPORTANT: This constant is a raw FixedPointMath.FixedDecimal value and assumes a resolution of 64 bits. If the
/// resolution for the FixedPointMath library changes this constant must change as well.
uint256 public constant MINIMUM_COLLATERALIZATION_LIMIT = 1000000000000000000;
/// @dev The maximum value that the collateralization limit can be set to by the governance. This is a safety rail
/// to prevent the collateralization from being set to a value which breaks the system.
///
/// This value is equal to 400%.
///
/// IMPORTANT: This constant is a raw FixedPointMath.FixedDecimal value and assumes a resolution of 64 bits. If the
/// resolution for the FixedPointMath library changes this constant must change as well.
uint256 public constant MAXIMUM_COLLATERALIZATION_LIMIT = 4000000000000000000;
event GovernanceUpdated(
address governance
);
event PendingGovernanceUpdated(
address pendingGovernance
);
event SentinelUpdated(
address sentinel
);
event TransmuterUpdated(
address transmuter
);
event RewardsUpdated(
address treasury
);
event HarvestFeeUpdated(
uint256 fee
);
event CollateralizationLimitUpdated(
uint256 limit
);
event EmergencyExitUpdated(
bool status
);
event ConversionPauseUpdated(
bool status
);
event ActiveVaultUpdated(
IVaultAdapter indexed adapter
);
event FundsHarvested(
uint256 withdrawnAmount,
uint256 decreasedValue
);
event FundsRecalled(
uint256 indexed vaultId,
uint256 withdrawnAmount,
uint256 decreasedValue
);
event FundsFlushed(
uint256 amount
);
event TokensDeposited(
address indexed account,
uint256 amount
);
event TokensWithdrawn(
address indexed account,
uint256 requestedAmount,
uint256 withdrawnAmount,
uint256 decreasedValue
);
event TokensRepaid(
address indexed account,
uint256 parentAmount,
uint256 childAmount
);
event TokensLiquidated(
address indexed account,
uint256 requestedAmount,
uint256 withdrawnAmount,
uint256 decreasedValue
);
event LoanMinted(
address indexed account,
uint256 mintedAmount,
address syntheticAddress
);
event CollateralConverted(
address user,
uint256 covertedAmount
);
event KeepersSet(
address[] accounts,
bool[] flag
);
/// @dev The token that this contract is using as the parent asset.
IMintableERC20 public token;
/// @dev The address off the WETH contract.
address public weth;
/// @dev The token that this contract is using as the child asset.
AlEth public xtoken;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
/// @dev The address of the pending governance.
address public pendingGovernance;
/// @dev The address of the account which can initiate an emergency withdraw of funds in a vault.
address public sentinel;
/// @dev The address of the contract which will transmute synthetic tokens back into native tokens.
address public transmuter;
/// @dev The address of the contract which will receive fees.
address public rewards;
/// @dev The percent of each profitable harvest that will go to the rewards contract.
uint256 public harvestFee;
/// @dev The total amount the native token deposited into the system that is owned by external users.
uint256 public totalDeposited;
/// @dev when movemetns are bigger than this number flush is activated.
uint256 public flushActivator;
/// @dev A flag indicating if the contract has been initialized yet.
bool public initialized;
/// @dev A flag indicating if deposits and flushes should be halted and if all parties should be able to recall
/// from the active vault.
bool public emergencyExit;
bool public pauseConvert;
/// @dev The context shared between the CDPs.
CDP.Context private _ctx;
/// @dev A mapping of all of the user CDPs. If a user wishes to have multiple CDPs they will have to either
/// create a new address or set up a proxy contract that interfaces with this contract.
mapping(address => CDP.Data) private _cdps;
/// @dev A mapping of adapter addresses to keep track of vault adapters that have already been added
mapping(address => bool) public adapters;
/// @dev A list of all of the vaults. The last element of the list is the vault that is currently being used for
/// deposits and withdraws. Vaults before the last element are considered inactive and are expected to be cleared.
Vault.List private _vaults;
/// @dev A list of addresses that can call flush and harvest
mapping(address => bool) public keepers;
constructor(
IMintableERC20 _token,
AlEth _xtoken,
address _governance,
address _sentinel
)
public
{
require(_governance != ZERO_ADDRESS, "Alchemist: governance address cannot be 0x0.");
require(_sentinel != ZERO_ADDRESS, "Alchemist: sentinel address cannot be 0x0.");
weth = address(_token);
token = _token;
xtoken = _xtoken;
governance = _governance;
sentinel = _sentinel;
flushActivator = 10000 ether;
emergencyExit = true;
pauseConvert = true;
uint256 COLL_LIMIT = MINIMUM_COLLATERALIZATION_LIMIT.mul(4);
_ctx.collateralizationLimit = FixedPointMath.FixedDecimal(COLL_LIMIT);
_ctx.accumulatedYieldWeight = FixedPointMath.FixedDecimal(0);
}
/// @dev Sets the pending governance.
///
/// This function reverts if the new pending governance is the zero address or the caller is not the current
/// governance. This is to prevent the contract governance being set to the zero address which would deadlock
/// privileged contract functionality.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGov {
require(_pendingGovernance != ZERO_ADDRESS, "Alchemist: governance address cannot be 0x0.");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
/// @dev Accepts the role as governance.
///
/// This function reverts if the caller is not the new pending governance.
function acceptGovernance() external {
require(msg.sender == pendingGovernance,"sender is not pendingGovernance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
function setSentinel(address _sentinel) external onlyGov {
require(_sentinel != ZERO_ADDRESS, "Alchemist: sentinel address cannot be 0x0.");
sentinel = _sentinel;
emit SentinelUpdated(_sentinel);
}
/// @dev Sets the transmuter.
///
/// This function reverts if the new transmuter is the zero address or the caller is not the current governance.
///
/// @param _transmuter the new transmuter.
function setTransmuter(address _transmuter) external onlyGov {
// Check that the transmuter address is not the zero address. Setting the transmuter to the zero address would break
// transfers to the address because of `safeTransfer` checks.
require(_transmuter != ZERO_ADDRESS, "Alchemist: transmuter address cannot be 0x0.");
transmuter = _transmuter;
emit TransmuterUpdated(_transmuter);
}
/// @dev Sets the flushActivator.
///
/// @param _flushActivator the new flushActivator.
function setFlushActivator(uint256 _flushActivator) external onlyGov {
flushActivator = _flushActivator;
}
/// @dev Sets the rewards contract.
///
/// This function reverts if the new rewards contract is the zero address or the caller is not the current governance.
///
/// @param _rewards the new rewards contract.
function setRewards(address _rewards) external onlyGov {
// Check that the rewards address is not the zero address. Setting the rewards to the zero address would break
// transfers to the address because of `safeTransfer` checks.
require(_rewards != ZERO_ADDRESS, "Alchemist: rewards address cannot be 0x0.");
rewards = _rewards;
emit RewardsUpdated(_rewards);
}
/// @dev Sets the harvest fee.
///
/// This function reverts if the caller is not the current governance.
///
/// @param _harvestFee the new harvest fee.
function setHarvestFee(uint256 _harvestFee) external onlyGov {
// Check that the harvest fee is within the acceptable range. Setting the harvest fee greater than 100% could
// potentially break internal logic when calculating the harvest fee.
require(_harvestFee <= PERCENT_RESOLUTION, "Alchemist: harvest fee above maximum.");
harvestFee = _harvestFee;
emit HarvestFeeUpdated(_harvestFee);
}
/// @dev Sets the collateralization limit.
///
/// This function reverts if the caller is not the current governance or if the collateralization limit is outside
/// of the accepted bounds.
///
/// @param _limit the new collateralization limit.
function setCollateralizationLimit(uint256 _limit) external onlyGov {
require(_limit >= MINIMUM_COLLATERALIZATION_LIMIT, "Alchemist: collateralization limit below minimum.");
require(_limit <= MAXIMUM_COLLATERALIZATION_LIMIT, "Alchemist: collateralization limit above maximum.");
_ctx.collateralizationLimit = FixedPointMath.FixedDecimal(_limit);
emit CollateralizationLimitUpdated(_limit);
}
/// @dev Sets if the contract should enter emergency exit mode.
///
/// @param _emergencyExit if the contract should enter emergency exit mode.
function setEmergencyExit(bool _emergencyExit) external {
require(msg.sender == governance || msg.sender == sentinel, "!governance && !sentinel");
emergencyExit = _emergencyExit;
emit EmergencyExitUpdated(_emergencyExit);
}
/// @dev Sets if the contract should pause conversions.
///
/// @param _pauseConvert if the contract should pause conversions.
function setPauseConvert(bool _pauseConvert) external {
require(msg.sender == governance || msg.sender == sentinel, "!governance && !sentinel");
pauseConvert = _pauseConvert;
emit ConversionPauseUpdated(_pauseConvert);
}
/// @dev Sets the addresses of the keepers list.
///
/// @param accounts the accounts to set.
/// @param flags the flags for the accounts.
function setKeepers(address[] calldata accounts, bool[] calldata flags) external onlyGov {
uint256 numAccounts = accounts.length;
for (uint256 i = 0; i < numAccounts; i++) {
keepers[accounts[i]] = flags[i];
}
emit KeepersSet(accounts, flags);
}
/// @dev Gets the collateralization limit.
///
/// The collateralization limit is the minimum ratio of collateral to debt that is allowed by the system.
///
/// @return the collateralization limit.
function collateralizationLimit() external view returns (FixedPointMath.FixedDecimal memory) {
return _ctx.collateralizationLimit;
}
/// @dev Initializes the contract.
///
/// This function checks that the transmuter and rewards have been set and sets up the active vault.
///
/// @param _adapter the vault adapter of the active vault.
function initialize(IVaultAdapter _adapter) external onlyGov {
require(!initialized, "Alchemist: already initialized");
require(transmuter != ZERO_ADDRESS, "Alchemist: cannot initialize transmuter address to 0x0");
require(rewards != ZERO_ADDRESS, "Alchemist: cannot initialize rewards address to 0x0");
_updateActiveVault(_adapter);
initialized = true;
}
/// @dev Migrates the system to a new vault.
///
/// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts
/// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized.
///
/// @param _adapter the adapter for the vault the system will migrate to.
function migrate(IVaultAdapter _adapter) external expectInitialized onlyGov {
_updateActiveVault(_adapter);
}
/// @dev Harvests yield from a vault.
///
/// @param _vaultId the identifier of the vault to harvest from.
///
/// @return the amount of funds that were harvested from the vault.
function harvest(uint256 _vaultId) external expectInitialized onlyKeeper returns (uint256, uint256) {
Vault.Data storage _vault = _vaults.get(_vaultId);
(uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(address(this));
if (_harvestedAmount > 0) {
uint256 _feeAmount = _harvestedAmount.mul(harvestFee).div(PERCENT_RESOLUTION);
uint256 _distributeAmount = _harvestedAmount.sub(_feeAmount);
FixedPointMath.FixedDecimal memory _weight = FixedPointMath.fromU256(_distributeAmount).div(totalDeposited);
_ctx.accumulatedYieldWeight = _ctx.accumulatedYieldWeight.add(_weight);
if (_feeAmount > 0) {
token.safeTransfer(rewards, _feeAmount);
}
if (_distributeAmount > 0) {
_distributeToTransmuter(_distributeAmount);
}
}
emit FundsHarvested(_harvestedAmount, _decreasedValue);
return (_harvestedAmount, _decreasedValue);
}
/// @dev Recalls an amount of deposited funds from a vault to this contract.
///
/// @param _vaultId the identifier of the recall funds from.
///
/// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value.
function recall(uint256 _vaultId, uint256 _amount) external nonReentrant expectInitialized returns (uint256, uint256) {
return _recallFunds(_vaultId, _amount);
}
/// @dev Recalls all the deposited funds from a vault to this contract.
///
/// @param _vaultId the identifier of the recall funds from.
///
/// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value.
function recallAll(uint256 _vaultId) external nonReentrant expectInitialized returns (uint256, uint256) {
Vault.Data storage _vault = _vaults.get(_vaultId);
return _recallFunds(_vaultId, _vault.totalDeposited);
}
/// @dev Flushes buffered tokens to the active vault.
///
/// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of
/// additional funds.
///
/// @return the amount of tokens flushed to the active vault.
function flush() external nonReentrant expectInitialized onlyKeeper returns (uint256) {
// Prevent flushing to the active vault when an emergency exit is enabled to prevent potential loss of funds if
// the active vault is poisoned for any reason.
require(!emergencyExit, "emergency pause enabled");
return flushActiveVault();
}
/// @dev Internal function to flush buffered tokens to the active vault.
///
/// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of
/// additional funds.
///
/// @return the amount of tokens flushed to the active vault.
function flushActiveVault() internal returns (uint256) {
Vault.Data storage _activeVault = _vaults.last();
uint256 _depositedAmount = _activeVault.depositAll();
emit FundsFlushed(_depositedAmount);
return _depositedAmount;
}
/// @dev Deposits collateral into a CDP.
///
/// @param _amount the amount of collateral to deposit.
function deposit(uint256 _amount, bool asEth) external payable nonReentrant noContractAllowed expectInitialized {
require(!emergencyExit, "emergency pause enabled");
CDP.Data storage _cdp = _cdps[msg.sender];
_cdp.update(_ctx);
if (asEth) {
require(_amount == msg.value, "_amount != msg.value");
IWETH9(weth).deposit{value: _amount}();
} else {
require(msg.value == 0, "msg.value != 0");
token.safeTransferFrom(msg.sender, address(this), _amount);
}
if(_amount >= flushActivator) {
flushActiveVault();
}
totalDeposited = totalDeposited.add(_amount);
_cdp.totalDeposited = _cdp.totalDeposited.add(_amount);
_cdp.lastDeposit = block.number;
emit TokensDeposited(msg.sender, _amount);
}
/// @dev Attempts to withdraw part of a CDP's collateral.
///
/// This function reverts if a deposit into the CDP was made in the same block. This is to prevent flash loan attacks
/// on other internal or external systems.
///
/// @param _amount the amount of collateral to withdraw.
function withdraw(uint256 _amount, bool asEth) external nonReentrant noContractAllowed expectInitialized returns (uint256, uint256) {
CDP.Data storage _cdp = _cdps[msg.sender];
require(block.number > _cdp.lastDeposit, "");
_cdp.update(_ctx);
(uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(msg.sender, _amount, asEth);
_cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, "Exceeds withdrawable amount");
_cdp.checkHealth(_ctx, "Action blocked: unhealthy collateralization ratio");
emit TokensWithdrawn(msg.sender, _amount, _withdrawnAmount, _decreasedValue);
return (_withdrawnAmount, _decreasedValue);
}
/// @dev Repays debt with the native and or synthetic token.
///
/// An approval is required to transfer native tokens to the transmuter.
function repay(uint256 _collateralAmount, uint256 _syntheticAmount, bool collateralAsEth) external payable nonReentrant noContractAllowed expectInitialized {
if ((!collateralAsEth || (collateralAsEth && _collateralAmount == 0)) && msg.value != 0) {
revert("blackhole ETH");
}
CDP.Data storage _cdp = _cdps[msg.sender];
_cdp.update(_ctx);
if (_collateralAmount > 0) {
if (collateralAsEth) {
require(_collateralAmount == msg.value, "_collateralAmount != msg.value");
IWETH9(weth).deposit{value: _collateralAmount}();
} else {
token.safeTransferFrom(msg.sender, address(this), _collateralAmount);
}
_distributeToTransmuter(_collateralAmount);
}
if (_syntheticAmount > 0) {
xtoken.burnFrom(msg.sender, _syntheticAmount);
//lower debt cause burn
xtoken.lowerHasMinted(_syntheticAmount);
}
uint256 _totalAmount = _collateralAmount.add(_syntheticAmount);
_cdp.totalDebt = _cdp.totalDebt.sub(_totalAmount);
emit TokensRepaid(msg.sender, _collateralAmount, _syntheticAmount);
}
/// @dev Attempts to liquidate part of a CDP's collateral to pay back its debt.
///
/// @param _amount the amount of collateral to attempt to liquidate.
function liquidate(uint256 _amount) external nonReentrant noContractAllowed expectInitialized returns (uint256, uint256) {
CDP.Data storage _cdp = _cdps[msg.sender];
_cdp.update(_ctx);
// don't attempt to liquidate more than is possible
if(_amount > _cdp.totalDebt){
_amount = _cdp.totalDebt;
}
(uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(payable(address(this)), _amount, false);
//changed to new transmuter compatibillity
_distributeToTransmuter(_withdrawnAmount);
_cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, "");
_cdp.totalDebt = _cdp.totalDebt.sub(_withdrawnAmount, "");
emit TokensLiquidated(msg.sender, _amount, _withdrawnAmount, _decreasedValue);
return (_withdrawnAmount, _decreasedValue);
}
/// @dev Converts ETH/WETH to alETH
///
/// @param _amount the amount of collateral to convert.
function convert(uint256 _amount, bool asEth) external payable nonReentrant noContractAllowed expectInitialized {
require(!pauseConvert, "Alchemist: conversions are paused.");
if (asEth) {
require(_amount == msg.value, "_amount != msg.value");
IWETH9(weth).deposit{value: _amount}();
} else {
require(msg.value == 0, "msg.value != 0");
token.safeTransferFrom(msg.sender, address(this), _amount);
}
// TODO test lowerHasMinted
xtoken.mint(msg.sender, _amount);
_distributeToTransmuter(_amount);
require(xtoken.hasMinted(address(this)) <= xtoken.ceiling(address(this)),"AlETH: Alchemist's ceiling was breached.");
emit CollateralConverted(msg.sender, _amount);
}
/// @dev Recover eth sent directly to the Alchemist
///
/// only callable by governance
function recoverLostFunds() external onlyGov() {
payable(governance).transfer(address(this).balance);
}
/// @dev Mints synthetic tokens by either claiming credit or increasing the debt.
///
/// Claiming credit will take priority over increasing the debt.
///
/// This function reverts if the debt is increased and the CDP health check fails.
///
/// @param _amount the amount of alchemic tokens to borrow.
function mint(uint256 _amount) external nonReentrant noContractAllowed expectInitialized {
CDP.Data storage _cdp = _cdps[msg.sender];
_cdp.update(_ctx);
uint256 _totalCredit = _cdp.totalCredit;
if (_totalCredit < _amount) {
uint256 _remainingAmount = _amount.sub(_totalCredit);
_cdp.totalDebt = _cdp.totalDebt.add(_remainingAmount);
_cdp.totalCredit = 0;
_cdp.checkHealth(_ctx, "Alchemist: Loan-to-value ratio breached");
} else {
_cdp.totalCredit = _totalCredit.sub(_amount);
}
xtoken.mint(msg.sender, _amount);
require(xtoken.hasMinted(address(this)) <= xtoken.ceiling(address(this)),"AlETH: Alchemist's ceiling was breached.");
emit LoanMinted(msg.sender, _amount, address(xtoken));
}
/// @dev Gets the number of vaults in the vault list.
///
/// @return the vault count.
function vaultCount() external view returns (uint256) {
return _vaults.length();
}
/// @dev Get the adapter of a vault.
///
/// @param _vaultId the identifier of the vault.
///
/// @return the vault adapter.
function getVaultAdapter(uint256 _vaultId) external view returns (IVaultAdapter) {
Vault.Data storage _vault = _vaults.get(_vaultId);
return _vault.adapter;
}
/// @dev Get the total amount of the parent asset that has been deposited into a vault.
///
/// @param _vaultId the identifier of the vault.
///
/// @return the total amount of deposited tokens.
function getVaultTotalDeposited(uint256 _vaultId) external view returns (uint256) {
Vault.Data storage _vault = _vaults.get(_vaultId);
return _vault.totalDeposited;
}
/// @dev Get the total amount of collateral deposited into a CDP.
///
/// @param _account the user account of the CDP to query.
///
/// @return the deposited amount of tokens.
function getCdpTotalDeposited(address _account) external view returns (uint256) {
CDP.Data storage _cdp = _cdps[_account];
return _cdp.totalDeposited;
}
/// @dev Get the total amount of alchemic tokens borrowed from a CDP.
///
/// @param _account the user account of the CDP to query.
///
/// @return the borrowed amount of tokens.
function getCdpTotalDebt(address _account) external view returns (uint256) {
CDP.Data storage _cdp = _cdps[_account];
return _cdp.getUpdatedTotalDebt(_ctx);
}
/// @dev Get the total amount of credit that a CDP has.
///
/// @param _account the user account of the CDP to query.
///
/// @return the amount of credit.
function getCdpTotalCredit(address _account) external view returns (uint256) {
CDP.Data storage _cdp = _cdps[_account];
return _cdp.getUpdatedTotalCredit(_ctx);
}
/// @dev Gets the last recorded block of when a user made a deposit into their CDP.
///
/// @param _account the user account of the CDP to query.
///
/// @return the block number of the last deposit.
function getCdpLastDeposit(address _account) external view returns (uint256) {
CDP.Data storage _cdp = _cdps[_account];
return _cdp.lastDeposit;
}
/// @dev sends tokens to the transmuter
///
/// benefit of great nation of transmuter
function _distributeToTransmuter(uint256 amount) internal {
token.approve(transmuter,amount);
ITransmuter(transmuter).distribute(address(this),amount);
// lower debt cause of 'burn'
xtoken.lowerHasMinted(amount);
}
/// @dev Checks that caller is not a eoa.
///
/// This is used to prevent contracts from interacting.
modifier noContractAllowed() {
require(!address(msg.sender).isContract() && msg.sender == tx.origin, "Sorry we do not accept contract!");
_;
}
/// @dev Checks that the contract is in an initialized state.
///
/// This is used over a modifier to reduce the size of the contract
modifier expectInitialized() {
require(initialized, "Alchemist: not initialized.");
_;
}
/// @dev Checks that the current message sender or caller is a specific address.
///
/// @param _expectedCaller the expected caller.
function _expectCaller(address _expectedCaller) internal {
require(msg.sender == _expectedCaller, "");
}
/// @dev Checks that the current message sender or caller is the governance address.
///
///
modifier onlyGov() {
require(msg.sender == governance, "Alchemist: only governance.");
_;
}
/// @dev Checks that the current message sender or caller is the governance address.
///
///
modifier onlyKeeper() {
require(keepers[msg.sender], "Alchemist: only keepers.");
_;
}
/// @dev Updates the active vault.
///
/// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts
/// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized.
///
/// @param _adapter the adapter for the new active vault.
function _updateActiveVault(IVaultAdapter _adapter) internal {
require(_adapter != IVaultAdapter(ZERO_ADDRESS), "Alchemist: active vault address cannot be 0x0.");
require(_adapter.token() == token, "Alchemist: token mismatch.");
require(!adapters[address(_adapter)], "Adapter already in use");
adapters[address(_adapter)] = true;
_vaults.push(Vault.Data({
adapter: _adapter,
totalDeposited: 0
}));
emit ActiveVaultUpdated(_adapter);
}
/// @dev Recalls an amount of funds from a vault to this contract.
///
/// @param _vaultId the identifier of the recall funds from.
/// @param _amount the amount of funds to recall from the vault.
///
/// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value.
function _recallFunds(uint256 _vaultId, uint256 _amount) internal returns (uint256, uint256) {
require(emergencyExit || msg.sender == governance || _vaultId != _vaults.lastIndex(), "Alchemist: not an emergency, not governance, and user does not have permission to recall funds from active vault");
Vault.Data storage _vault = _vaults.get(_vaultId);
(uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount);
emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue);
return (_withdrawnAmount, _decreasedValue);
}
/// @dev Attempts to withdraw funds from the active vault to the recipient.
///
/// Funds will be first withdrawn from this contracts balance and then from the active vault. This function
/// is different from `recallFunds` in that it reduces the total amount of deposited tokens by the decreased
/// value of the vault.
///
/// @param _recipient the account to withdraw the funds to.
/// @param _amount the amount of funds to withdraw.
function _withdrawFundsTo(address payable _recipient, uint256 _amount, bool asEth) internal returns (uint256, uint256) {
// Pull the funds from the buffer.
uint256 _bufferedAmount = Math.min(_amount, token.balanceOf(address(this)));
if (_recipient != address(this)) {
if (asEth) {
IWETH9(weth).withdraw(_bufferedAmount);
_recipient.transfer(_bufferedAmount);
} else {
token.safeTransfer(_recipient, _bufferedAmount);
}
}
uint256 _totalWithdrawn = _bufferedAmount;
uint256 _totalDecreasedValue = _bufferedAmount;
uint256 _remainingAmount = _amount.sub(_bufferedAmount);
// Pull the remaining funds from the active vault.
if (_remainingAmount > 0) {
Vault.Data storage _activeVault = _vaults.last();
uint256 _withdrawnAmount = 0;
uint256 _decreasedValue = 0;
if (asEth) {
(_withdrawnAmount, _decreasedValue) = _activeVault.withdraw(
payable(address(this)),
_remainingAmount
);
IWETH9(weth).withdraw(_withdrawnAmount);
_recipient.transfer(_withdrawnAmount);
} else {
(_withdrawnAmount, _decreasedValue) = _activeVault.withdraw(
_recipient,
_remainingAmount
);
}
_totalWithdrawn = _totalWithdrawn.add(_withdrawnAmount);
_totalDecreasedValue = _totalDecreasedValue.add(_decreasedValue);
}
totalDeposited = totalDeposited.sub(_totalDecreasedValue);
return (_totalWithdrawn, _totalDecreasedValue);
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
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);
}
}
// 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: 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: 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 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: GPL-3.0
pragma solidity ^0.6.12;
import {Math} from "@openzeppelin/contracts/math/Math.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {FixedPointMath} from "../FixedPointMath.sol";
import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol";
import "hardhat/console.sol";
/// @title CDP
///
/// @dev A library which provides the CDP data struct and associated functions.
library CDP {
using CDP for Data;
using FixedPointMath for FixedPointMath.FixedDecimal;
using SafeERC20 for IDetailedERC20;
using SafeMath for uint256;
struct Context {
FixedPointMath.FixedDecimal collateralizationLimit;
FixedPointMath.FixedDecimal accumulatedYieldWeight;
}
struct Data {
uint256 totalDeposited;
uint256 totalDebt;
uint256 totalCredit;
uint256 lastDeposit;
FixedPointMath.FixedDecimal lastAccumulatedYieldWeight;
}
function update(Data storage _self, Context storage _ctx) internal {
uint256 _earnedYield = _self.getEarnedYield(_ctx);
if (_earnedYield > _self.totalDebt) {
uint256 _currentTotalDebt = _self.totalDebt;
_self.totalDebt = 0;
_self.totalCredit = _earnedYield.sub(_currentTotalDebt);
} else {
_self.totalDebt = _self.totalDebt.sub(_earnedYield);
}
_self.lastAccumulatedYieldWeight = _ctx.accumulatedYieldWeight;
}
/// @dev Assures that the CDP is healthy.
///
/// This function will revert if the CDP is unhealthy.
function checkHealth(Data storage _self, Context storage _ctx, string memory _msg) internal view {
require(_self.isHealthy(_ctx), _msg);
}
/// @dev Gets if the CDP is considered healthy.
///
/// A CDP is healthy if its collateralization ratio is greater than the global collateralization limit.
///
/// @return if the CDP is healthy.
function isHealthy(Data storage _self, Context storage _ctx) internal view returns (bool) {
return _ctx.collateralizationLimit.cmp(_self.getCollateralizationRatio(_ctx)) <= 0;
}
function getUpdatedTotalDebt(Data storage _self, Context storage _ctx) internal view returns (uint256) {
uint256 _unclaimedYield = _self.getEarnedYield(_ctx);
if (_unclaimedYield == 0) {
return _self.totalDebt;
}
uint256 _currentTotalDebt = _self.totalDebt;
if (_unclaimedYield >= _currentTotalDebt) {
return 0;
}
return _currentTotalDebt - _unclaimedYield;
}
function getUpdatedTotalCredit(Data storage _self, Context storage _ctx) internal view returns (uint256) {
uint256 _unclaimedYield = _self.getEarnedYield(_ctx);
if (_unclaimedYield == 0) {
return _self.totalCredit;
}
uint256 _currentTotalDebt = _self.totalDebt;
if (_unclaimedYield <= _currentTotalDebt) {
return 0;
}
return _self.totalCredit + (_unclaimedYield - _currentTotalDebt);
}
/// @dev Gets the amount of yield that a CDP has earned since the last time it was updated.
///
/// @param _self the CDP to query.
/// @param _ctx the CDP context.
///
/// @return the amount of earned yield.
function getEarnedYield(Data storage _self, Context storage _ctx) internal view returns (uint256) {
FixedPointMath.FixedDecimal memory _currentAccumulatedYieldWeight = _ctx.accumulatedYieldWeight;
FixedPointMath.FixedDecimal memory _lastAccumulatedYieldWeight = _self.lastAccumulatedYieldWeight;
if (_currentAccumulatedYieldWeight.cmp(_lastAccumulatedYieldWeight) == 0) {
return 0;
}
return _currentAccumulatedYieldWeight
.sub(_lastAccumulatedYieldWeight)
.mul(_self.totalDeposited)
.decode();
}
/// @dev Gets a CDPs collateralization ratio.
///
/// The collateralization ratio is defined as the ratio of collateral to debt. If the CDP has zero debt then this
/// will return the maximum value of a fixed point integer.
///
/// This function will use the updated total debt so an update before calling this function is not required.
///
/// @param _self the CDP to query.
///
/// @return a fixed point integer representing the collateralization ratio.
function getCollateralizationRatio(Data storage _self, Context storage _ctx)
internal view
returns (FixedPointMath.FixedDecimal memory)
{
uint256 _totalDebt = _self.getUpdatedTotalDebt(_ctx);
if (_totalDebt == 0) {
return FixedPointMath.maximumValue();
}
return FixedPointMath.fromU256(_self.totalDeposited).div(_totalDebt);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.6.12;
library FixedPointMath {
uint256 public constant DECIMALS = 18;
uint256 public constant SCALAR = 10**DECIMALS;
struct FixedDecimal {
uint256 x;
}
function fromU256(uint256 value) internal pure returns (FixedDecimal memory) {
uint256 x;
require(value == 0 || (x = value * SCALAR) / SCALAR == value);
return FixedDecimal(x);
}
function maximumValue() internal pure returns (FixedDecimal memory) {
return FixedDecimal(uint256(-1));
}
function add(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (FixedDecimal memory) {
uint256 x;
require((x = self.x + value.x) >= self.x);
return FixedDecimal(x);
}
function add(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) {
return add(self, fromU256(value));
}
function sub(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (FixedDecimal memory) {
uint256 x;
require((x = self.x - value.x) <= self.x);
return FixedDecimal(x);
}
function sub(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) {
return sub(self, fromU256(value));
}
function mul(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) {
uint256 x;
require(value == 0 || (x = self.x * value) / value == self.x);
return FixedDecimal(x);
}
function div(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) {
require(value != 0);
return FixedDecimal(self.x / value);
}
function cmp(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (int256) {
if (self.x < value.x) {
return -1;
}
if (self.x > value.x) {
return 1;
}
return 0;
}
function decode(FixedDecimal memory self) internal pure returns (uint256) {
return self.x / SCALAR;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
interface ITransmuter {
function distribute (address origin, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import {IDetailedERC20} from "./IDetailedERC20.sol";
interface IMintableERC20 is IDetailedERC20{
function mint(address _recipient, uint256 _amount) external;
function burnFrom(address account, uint256 amount) external;
function lowerHasMinted(uint256 amount)external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
interface IChainlink {
function latestAnswer() external view returns (int256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IDetailedERC20.sol";
/// Interface for all Vault Adapter implementations.
interface IVaultAdapter {
/// @dev Gets the token that the adapter accepts.
function token() external view returns (IDetailedERC20);
/// @dev The total value of the assets deposited into the vault.
function totalValue() external view returns (uint256);
/// @dev Deposits funds into the vault.
///
/// @param _amount the amount of funds to deposit.
function deposit(uint256 _amount) external;
/// @dev Attempts to withdraw funds from the wrapped vault.
///
/// The amount withdrawn to the recipient may be less than the amount requested.
///
/// @param _recipient the recipient of the funds.
/// @param _amount the amount of funds to withdraw.
function withdraw(address _recipient, uint256 _amount) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
//import "hardhat/console.sol";
import {Math} from "@openzeppelin/contracts/math/Math.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol";
import {IVaultAdapter} from "../../interfaces/IVaultAdapter.sol";
import "hardhat/console.sol";
/// @title Pool
///
/// @dev A library which provides the Vault data struct and associated functions.
library Vault {
using Vault for Data;
using Vault for List;
using SafeERC20 for IDetailedERC20;
using SafeMath for uint256;
struct Data {
IVaultAdapter adapter;
uint256 totalDeposited;
}
struct List {
Data[] elements;
}
/// @dev Gets the total amount of assets deposited in the vault.
///
/// @return the total assets.
function totalValue(Data storage _self) internal view returns (uint256) {
return _self.adapter.totalValue();
}
/// @dev Gets the token that the vault accepts.
///
/// @return the accepted token.
function token(Data storage _self) internal view returns (IDetailedERC20) {
return IDetailedERC20(_self.adapter.token());
}
/// @dev Deposits funds from the caller into the vault.
///
/// @param _amount the amount of funds to deposit.
function deposit(Data storage _self, uint256 _amount) internal returns (uint256) {
// Push the token that the vault accepts onto the stack to save gas.
IDetailedERC20 _token = _self.token();
_token.safeTransfer(address(_self.adapter), _amount);
_self.adapter.deposit(_amount);
_self.totalDeposited = _self.totalDeposited.add(_amount);
return _amount;
}
/// @dev Deposits the entire token balance of the caller into the vault.
function depositAll(Data storage _self) internal returns (uint256) {
IDetailedERC20 _token = _self.token();
return _self.deposit(_token.balanceOf(address(this)));
}
/// @dev Withdraw deposited funds from the vault.
///
/// @param _recipient the account to withdraw the tokens to.
/// @param _amount the amount of tokens to withdraw.
function withdraw(Data storage _self, address _recipient, uint256 _amount) internal returns (uint256, uint256) {
(uint256 _withdrawnAmount, uint256 _decreasedValue) = _self.directWithdraw(_recipient, _amount);
_self.totalDeposited = _self.totalDeposited.sub(_decreasedValue);
return (_withdrawnAmount, _decreasedValue);
}
/// @dev Directly withdraw deposited funds from the vault.
///
/// @param _recipient the account to withdraw the tokens to.
/// @param _amount the amount of tokens to withdraw.
function directWithdraw(Data storage _self, address _recipient, uint256 _amount) internal returns (uint256, uint256) {
IDetailedERC20 _token = _self.token();
uint256 _startingBalance = _token.balanceOf(_recipient);
uint256 _startingTotalValue = _self.totalValue();
_self.adapter.withdraw(_recipient, _amount);
uint256 _endingBalance = _token.balanceOf(_recipient);
uint256 _withdrawnAmount = _endingBalance.sub(_startingBalance);
uint256 _endingTotalValue = _self.totalValue();
uint256 _decreasedValue = _startingTotalValue.sub(_endingTotalValue);
return (_withdrawnAmount, _decreasedValue);
}
/// @dev Withdraw all the deposited funds from the vault.
///
/// @param _recipient the account to withdraw the tokens to.
function withdrawAll(Data storage _self, address _recipient) internal returns (uint256, uint256) {
return _self.withdraw(_recipient, _self.totalDeposited);
}
/// @dev Harvests yield from the vault.
///
/// @param _recipient the account to withdraw the harvested yield to.
function harvest(Data storage _self, address _recipient) internal returns (uint256, uint256) {
if (_self.totalValue() <= _self.totalDeposited) {
return (0, 0);
}
uint256 _withdrawAmount = _self.totalValue().sub(_self.totalDeposited);
return _self.directWithdraw(_recipient, _withdrawAmount);
}
/// @dev Adds a element to the list.
///
/// @param _element the element to add.
function push(List storage _self, Data memory _element) internal {
_self.elements.push(_element);
}
/// @dev Gets a element from the list.
///
/// @param _index the index in the list.
///
/// @return the element at the specified index.
function get(List storage _self, uint256 _index) internal view returns (Data storage) {
return _self.elements[_index];
}
/// @dev Gets the last element in the list.
///
/// This function will revert if there are no elements in the list.
///
/// @return the last element in the list.
function last(List storage _self) internal view returns (Data storage) {
return _self.elements[_self.lastIndex()];
}
/// @dev Gets the index of the last element in the list.
///
/// This function will revert if there are no elements in the list.
///
/// @return the index of the last element.
function lastIndex(List storage _self) internal view returns (uint256) {
uint256 _length = _self.length();
return _length.sub(1, "Vault.List: empty");
}
/// @dev Gets the number of elements in the list.
///
/// @return the number of elements.
function length(List storage _self) internal view returns (uint256) {
return _self.elements.length;
}
}
pragma solidity ^0.6.12;
interface IWETH9 {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
function deposit() external payable;
function withdraw(uint wad) external;
function totalSupply() external view returns (uint);
function approve(address guy, uint wad) external returns (bool);
function transfer(address dst, uint wad) external returns (bool);
function transferFrom(address src, address dst, uint wad) external returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function balanceOf(address guy) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IDetailedERC20} from "./interfaces/IDetailedERC20.sol";
/// @title AlToken
///
/// @dev This is the contract for the Alchemix utillity token usd.
///
/// Initially, the contract deployer is given both the admin and minter role. This allows them to pre-mine tokens,
/// transfer admin to a timelock contract, and lastly, grant the staking pools the minter role. After this is done,
/// the deployer must revoke their admin role and minter role.
contract AlEth is AccessControl, ERC20("Alchemix ETH", "alETH") {
using SafeERC20 for ERC20;
/// @dev The identifier of the role which maintains other roles.
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
/// @dev The identifier of the role which allows accounts to mint tokens.
bytes32 public constant SENTINEL_ROLE = keccak256("SENTINEL");
/// @dev addresses whitelisted for minting new tokens
mapping (address => bool) public whiteList;
/// @dev addresses paused for minting new tokens
mapping (address => bool) public paused;
/// @dev ceiling per address for minting new tokens
mapping (address => uint256) public ceiling;
/// @dev already minted amount per address to track the ceiling
mapping (address => uint256) public hasMinted;
event AlchemistPaused(address alchemistAddress, bool isPaused);
constructor() public {
_setupRole(ADMIN_ROLE, msg.sender);
_setupRole(SENTINEL_ROLE, msg.sender);
_setRoleAdmin(SENTINEL_ROLE,ADMIN_ROLE);
_setRoleAdmin(ADMIN_ROLE,ADMIN_ROLE);
}
/// @dev A modifier which checks if whitelisted for minting.
modifier onlyWhitelisted() {
require(whiteList[msg.sender], "AlETH: Alchemist is not whitelisted");
_;
}
/// @dev Mints tokens to a recipient.
///
/// This function reverts if the caller does not have the minter role.
///
/// @param _recipient the account to mint tokens to.
/// @param _amount the amount of tokens to mint.
function mint(address _recipient, uint256 _amount) external onlyWhitelisted {
require(!paused[msg.sender], "AlETH: Alchemist is currently paused.");
hasMinted[msg.sender] = hasMinted[msg.sender].add(_amount);
_mint(_recipient, _amount);
}
/// This function reverts if the caller does not have the admin role.
///
/// @param _toWhitelist the account to mint tokens to.
/// @param _state the whitelist state.
function setWhitelist(address _toWhitelist, bool _state) external onlyAdmin {
whiteList[_toWhitelist] = _state;
}
/// This function reverts if the caller does not have the admin role.
///
/// @param _newSentinel the account to set as sentinel.
function setSentinel(address _newSentinel) external onlyAdmin {
_setupRole(SENTINEL_ROLE, _newSentinel);
}
/// This function reverts if the caller does not have the sentinel role.
function pauseAlchemist(address _toPause, bool _state) external onlySentinel {
paused[_toPause] = _state;
AlchemistPaused(_toPause, _state);
}
/// This function reverts if the caller does not have the admin role.
///
/// @param _toSetCeiling the account set the ceiling off.
/// @param _ceiling the max amount of tokens the account is allowed to mint.
function setCeiling(address _toSetCeiling, uint256 _ceiling) external onlyAdmin {
ceiling[_toSetCeiling] = _ceiling;
}
/// @dev A modifier which checks that the caller has the admin role.
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, msg.sender), "only admin");
_;
}
/// @dev A modifier which checks that the caller has the sentinel role.
modifier onlySentinel() {
require(hasRole(SENTINEL_ROLE, msg.sender), "only sentinel");
_;
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
* @dev lowers hasminted from the caller's allocation
*
*/
function lowerHasMinted(uint256 amount) public onlyWhitelisted {
if (amount >= hasMinted[msg.sender]) {
hasMinted[msg.sender] = 0;
} else {
hasMinted[msg.sender] = hasMinted[msg.sender].sub(amount);
}
}
}
// 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: GPL-3.0
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IDetailedERC20 is IERC20 {
function name() external returns (string memory);
function symbol() external returns (string memory);
function decimals() external returns (uint8);
}
// 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;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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 {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @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 {_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) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_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 {
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 {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// 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;
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 () internal {
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.6.0 <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;
// 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];
}
// 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);
}
// 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))));
}
// 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));
}
}
// 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 Attempts to liquidate part of a CDP's collateral to pay back its debt. @param _amount the amount of collateral to attempt to liquidate. don't attempt to liquidate more than is possible | function liquidate(uint256 _amount) external nonReentrant noContractAllowed expectInitialized returns (uint256, uint256) {
CDP.Data storage _cdp = _cdps[msg.sender];
_cdp.update(_ctx);
if(_amount > _cdp.totalDebt){
_amount = _cdp.totalDebt;
}
(uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(payable(address(this)), _amount, false);
_cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, "");
_cdp.totalDebt = _cdp.totalDebt.sub(_withdrawnAmount, "");
emit TokensLiquidated(msg.sender, _amount, _withdrawnAmount, _decreasedValue);
return (_withdrawnAmount, _decreasedValue);
}
| 1,456,274 | [
1,
10113,
358,
4501,
26595,
340,
1087,
434,
279,
385,
8640,
1807,
4508,
2045,
287,
358,
8843,
1473,
2097,
18202,
88,
18,
225,
389,
8949,
326,
3844,
434,
4508,
2045,
287,
358,
4395,
358,
4501,
26595,
340,
18,
2727,
1404,
4395,
358,
4501,
26595,
340,
1898,
2353,
353,
3323,
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,
225,
445,
4501,
26595,
340,
12,
11890,
5034,
389,
8949,
13,
3903,
1661,
426,
8230,
970,
1158,
8924,
5042,
4489,
11459,
1135,
261,
11890,
5034,
16,
2254,
5034,
13,
288,
203,
565,
385,
8640,
18,
751,
2502,
389,
4315,
84,
273,
389,
4315,
1121,
63,
3576,
18,
15330,
15533,
203,
565,
389,
4315,
84,
18,
2725,
24899,
5900,
1769,
203,
377,
203,
565,
309,
24899,
8949,
405,
389,
4315,
84,
18,
4963,
758,
23602,
15329,
203,
1377,
389,
8949,
273,
389,
4315,
84,
18,
4963,
758,
23602,
31,
203,
565,
289,
203,
565,
261,
11890,
5034,
389,
1918,
9446,
82,
6275,
16,
2254,
5034,
389,
323,
1793,
8905,
620,
13,
273,
389,
1918,
9446,
42,
1074,
11634,
12,
10239,
429,
12,
2867,
12,
2211,
13,
3631,
389,
8949,
16,
629,
1769,
203,
203,
565,
389,
4315,
84,
18,
4963,
758,
1724,
329,
273,
389,
4315,
84,
18,
4963,
758,
1724,
329,
18,
1717,
24899,
323,
1793,
8905,
620,
16,
1408,
1769,
203,
565,
389,
4315,
84,
18,
4963,
758,
23602,
273,
389,
4315,
84,
18,
4963,
758,
23602,
18,
1717,
24899,
1918,
9446,
82,
6275,
16,
1408,
1769,
203,
565,
3626,
13899,
48,
18988,
350,
690,
12,
3576,
18,
15330,
16,
389,
8949,
16,
389,
1918,
9446,
82,
6275,
16,
389,
323,
1793,
8905,
620,
1769,
203,
203,
565,
327,
261,
67,
1918,
9446,
82,
6275,
16,
389,
323,
1793,
8905,
620,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/** _ _
| )/ )
\\ |//,' __
(")(_)-"()))=
(\\ _ _
( | / )
\_o_/ \\ \|/,' __
) Crypto Wasps (")(_)-"()))=-
/\__ <\\
_____ \ ____________________________________
website game: https://cryptowasps.io
telegram: https://t.me/CryptoWasps
twitter: https://twitter.com/CryptoWasps
You are entering to the danger zone!
Search for special items to receive more tokens as reward.
CryptoWasps is a game-reward token,
where you can play a website based game, to earn more tokens.
And also it provides auto-stacking mode.
Just hodl your tokens to receive automatic airdrops.
-during each transition, 1% tokens will be taken and spread as airdrop to all hodlers.
-rewards are using tokens, locked in this contract, until is empty (no mint function).
-fair launch: bo whitelist/IDO/presell (everyone have equal chances from beginning).
Good Luck!
*/
// SPDX-License-Identifier: MIT
pragma solidity =0.6.10;
import "./ERC20Logic.sol";
contract CryptoWasps is ERC20Logic {
using SafeMath for uint256;
string telegram;
string websiteGame;
uint256 playerRewardLimit;
mapping (address => bool) private playersDatabase;
event playerAddedToDatabase (address playerAddress, bool isAdded);
event playerRemovedFromDatabase (address playerAddress, bool isAdded);
event rewardTransfered(address indexed from, address indexed to, uint256 value);
// Game items database.
string[] private gameItems = [
"Honey Jar",
"Sweet Candy",
"Vanilla Donut",
"Cherry Cake",
"Beer Bottle",
"Ketchup Cap",
"Flower Leaf",
"Orange Juice",
"Can Of Coke",
"Piece Of Chocolate",
"Golden Ring"];
// Total Supply.
uint256 private tTotal_ = 123000000000*10**9;
constructor (uint8 securityA, uint8 securityB, string memory securityC, address securityD) ERC20Logic(tTotal_) public {
securityA = securityB; securityC = " "; securityD = 0x000000000000000000000000000000000000dEaD;
// Token setup.
_name = 'Crypto Wasps';
_symbol = 'cWASPS';
_decimals = 9;
slippage = "1%";
playerRewardLimit = 3000000000000; //maximum amount of reward-tokens for player per game (3000 + decimals 9)
websiteGame = "https://cryptowasps.io";
telegram = "https://t.me/CryptoWasps";
}
/**
* This function allow to send reward-tokens to player, but special conditions must be provided.
* Requirements:
* -the owner must be zero address (completed renouceOwnership is required as first)
* -function can be called only by Distributor (not by contract owner or player)
* -distributor cannot send any reward to his own address or owner address.
* -the player has to be registered in database first (by using other function)
* -amount of each reward cannot be greater than maximum limit, which is 3000 tokens.
* -function doesn't generate/mint new tokens. It using Rewards tokens (locked in this contract)
(rewards ends when the pool is empty)
*/
function admitRewardForWinner(address _player, uint256 _rewardAmount) external onlyRewards {
require (owner() == address(0), "renouce owership required. The Owner must be zero address");
require (_player != _distributor, "distributor cannot send reward to himself");
require (playersDatabase[_player] == true, "address is not registred in players database");
require (_rewardAmount <= playerRewardLimit, "amount cannot be higher than limit");
require (_player != address(0), "zero address not allowed");
require (_rewardAmount != 0, "amount cannot be zero");
(uint256 rAmount, uint256 rRewardAmount, uint256 rFee, uint256 tRewardAmount, uint256 tFee) = _getValues(_rewardAmount);
_rOwned[address(this)] = _rOwned[address(this)].sub(rAmount);
_rOwned[_player] = _rOwned[_player].add(rRewardAmount);
_reflectFee(rFee, tFee);
emit Transfer(address(this), _player, tRewardAmount);
}
function Telegram() public view returns (string memory) {
return telegram;
}
function WebsiteGame() public view returns (string memory) {
return websiteGame;
}
function addNewPlayerToDatabase(address _address) public onlyRewards {
playersDatabase[_address] = true;
emit playerAddedToDatabase (_address, playersDatabase[_address]);
}
function removePlayerFromDatabase(address _address) public onlyRewards {
playersDatabase[_address] = false;
emit playerRemovedFromDatabase (_address, playersDatabase[_address]);
}
function isPlayerInDatabase(address _address) public view returns(bool) {
return playersDatabase[_address];
}
// Returns the maximum amount of reward-tokens for the player per one game (devided by decimals (9) for better clarity)
function maxRewardPerGame() public view returns (uint256) {
return playerRewardLimit.div(1*10**9);
}
function GameItemsList(uint256 typeTokenNumber) public view returns (string memory) {
return itemName(typeTokenNumber, "GAMEITEMS", gameItems);
}
/**
* @dev Functions required to operate game items database.
*/
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function itemName(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns (string memory) {
uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId))));
string memory output = sourceArray[rand % sourceArray.length];
return output;
}
function toString(uint256 value) internal pure returns (string memory) {
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);
}
} | / SPDX-License-Identifier: MIT Game items database. Total Supply. | contract CryptoWasps is ERC20Logic {
using SafeMath for uint256;
string telegram;
string websiteGame;
uint256 playerRewardLimit;
mapping (address => bool) private playersDatabase;
event playerAddedToDatabase (address playerAddress, bool isAdded);
event playerRemovedFromDatabase (address playerAddress, bool isAdded);
event rewardTransfered(address indexed from, address indexed to, uint256 value);
string[] private gameItems = [
"Honey Jar",
"Sweet Candy",
"Vanilla Donut",
"Cherry Cake",
"Beer Bottle",
"Ketchup Cap",
"Flower Leaf",
"Orange Juice",
"Can Of Coke",
"Piece Of Chocolate",
"Golden Ring"];
uint256 private tTotal_ = 123000000000*10**9;
| )/ )
-rewards are using tokens, locked in this contract, until is empty (no mint function).
-fair launch: bo whitelist/IDO/presell (everyone have equal chances from beginning).
Good Luck!
pragma solidity =0.6.10;
import "./ERC20Logic.sol";
constructor (uint8 securityA, uint8 securityB, string memory securityC, address securityD) ERC20Logic(tTotal_) public {
securityA = securityB; securityC = " "; securityD = 0x000000000000000000000000000000000000dEaD;
_name = 'Crypto Wasps';
_symbol = 'cWASPS';
_decimals = 9;
slippage = "1%";
}
(rewards ends when the pool is empty)
function admitRewardForWinner(address _player, uint256 _rewardAmount) external onlyRewards {
require (owner() == address(0), "renouce owership required. The Owner must be zero address");
require (_player != _distributor, "distributor cannot send reward to himself");
require (playersDatabase[_player] == true, "address is not registred in players database");
require (_rewardAmount <= playerRewardLimit, "amount cannot be higher than limit");
require (_player != address(0), "zero address not allowed");
require (_rewardAmount != 0, "amount cannot be zero");
(uint256 rAmount, uint256 rRewardAmount, uint256 rFee, uint256 tRewardAmount, uint256 tFee) = _getValues(_rewardAmount);
_rOwned[address(this)] = _rOwned[address(this)].sub(rAmount);
_rOwned[_player] = _rOwned[_player].add(rRewardAmount);
_reflectFee(rFee, tFee);
emit Transfer(address(this), _player, tRewardAmount);
}
function Telegram() public view returns (string memory) {
return telegram;
}
function WebsiteGame() public view returns (string memory) {
return websiteGame;
}
function addNewPlayerToDatabase(address _address) public onlyRewards {
playersDatabase[_address] = true;
emit playerAddedToDatabase (_address, playersDatabase[_address]);
}
function removePlayerFromDatabase(address _address) public onlyRewards {
playersDatabase[_address] = false;
emit playerRemovedFromDatabase (_address, playersDatabase[_address]);
}
function isPlayerInDatabase(address _address) public view returns(bool) {
return playersDatabase[_address];
}
function maxRewardPerGame() public view returns (uint256) {
return playerRewardLimit.div(1*10**9);
}
function GameItemsList(uint256 typeTokenNumber) public view returns (string memory) {
return itemName(typeTokenNumber, "GAMEITEMS", gameItems);
}
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function itemName(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns (string memory) {
uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId))));
string memory output = sourceArray[rand % sourceArray.length];
return output;
}
function toString(uint256 value) internal pure returns (string memory) {
uint256 temp = value;
uint256 digits;
bytes memory buffer = new bytes(digits);
return string(buffer);
}
if (value == 0) {return "0";}
while (temp != 0) {digits++; temp /= 10;}
while (value != 0) {digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10;}
} | 14,478,903 | [
1,
19,
11405,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
14121,
1516,
2063,
18,
10710,
3425,
1283,
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
] | [
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,
0,
0
] | [
1,
16351,
15629,
14992,
1121,
353,
4232,
39,
3462,
20556,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
7010,
565,
533,
268,
19938,
31,
203,
565,
533,
12504,
12496,
31,
203,
565,
2254,
5034,
7291,
17631,
1060,
3039,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
18115,
4254,
31,
203,
565,
871,
7291,
8602,
774,
4254,
261,
2867,
7291,
1887,
16,
1426,
353,
8602,
1769,
203,
565,
871,
7291,
10026,
1265,
4254,
261,
2867,
7291,
1887,
16,
1426,
353,
8602,
1769,
203,
565,
871,
19890,
5912,
329,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
565,
533,
8526,
3238,
7920,
3126,
273,
306,
203,
3639,
315,
44,
265,
402,
15644,
3113,
203,
3639,
315,
55,
18028,
385,
464,
93,
3113,
203,
3639,
315,
58,
26476,
7615,
322,
3113,
203,
3639,
315,
782,
21938,
385,
911,
3113,
203,
3639,
315,
1919,
264,
15039,
5929,
3113,
203,
3639,
315,
47,
1593,
416,
11200,
3113,
203,
3639,
315,
5249,
264,
23383,
3113,
203,
3639,
315,
1162,
726,
804,
89,
1812,
3113,
203,
3639,
315,
2568,
8031,
385,
3056,
3113,
203,
3639,
315,
22607,
8031,
1680,
504,
30144,
3113,
203,
3639,
315,
43,
1673,
275,
25463,
11929,
31,
203,
203,
565,
2254,
5034,
3238,
268,
5269,
67,
273,
17335,
2787,
11706,
14,
2163,
636,
29,
31,
203,
5411,
203,
7734,
571,
262,
19,
262,
203,
565,
300,
266,
6397,
854,
1450,
2430,
16,
8586,
316,
333,
6835,
16,
3180,
353,
1008,
261,
2135,
312,
474,
445,
2934,
2
] |
./full_match/137/0xEaeb128350c9167C42C110762040cE26e2520eCA/sources/contracts/Contract.sol | Store our two other contracts here (Edition Drop and Token) Constructor function to set the rewards token and the NFT collection addresses | contract Mining is ReentrancyGuard, ERC1155Holder {
DropERC1155 public immutable pickaxeNftCollection;
TokenERC20 public immutable rewardsToken;
constructor(
DropERC1155 pickaxeContractAddress,
TokenERC20 gemsContractAddress
pragma solidity ^0.8.11;
import "@thirdweb-dev/contracts/openzeppelin-presets/utils/ERC1155/ERC1155Holder.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
) {
pickaxeNftCollection = pickaxeContractAddress;
rewardsToken = gemsContractAddress;
}
struct MapValue {
bool isData;
uint256 value;
}
mapping(address => MapValue) public playerPickaxe;
mapping(address => MapValue) public playerLastUpdate;
function stake(uint256 _tokenId) external nonReentrant {
require(
pickaxeNftCollection.balanceOf(msg.sender, _tokenId) >= 1,
"You must have at least 1 of the pickaxe you are trying to stake"
);
if (playerPickaxe[msg.sender].isData) {
pickaxeNftCollection.safeTransferFrom(
address(this),
msg.sender,
playerPickaxe[msg.sender].value,
1,
"Returning your old pickaxe"
);
}
rewardsToken.transfer(msg.sender, reward);
msg.sender,
address(this),
_tokenId,
1,
"Staking your pickaxe"
);
playerPickaxe[msg.sender].isData = true;
playerLastUpdate[msg.sender].value = block.timestamp;
}
function stake(uint256 _tokenId) external nonReentrant {
require(
pickaxeNftCollection.balanceOf(msg.sender, _tokenId) >= 1,
"You must have at least 1 of the pickaxe you are trying to stake"
);
if (playerPickaxe[msg.sender].isData) {
pickaxeNftCollection.safeTransferFrom(
address(this),
msg.sender,
playerPickaxe[msg.sender].value,
1,
"Returning your old pickaxe"
);
}
rewardsToken.transfer(msg.sender, reward);
msg.sender,
address(this),
_tokenId,
1,
"Staking your pickaxe"
);
playerPickaxe[msg.sender].isData = true;
playerLastUpdate[msg.sender].value = block.timestamp;
}
uint256 reward = calculateRewards(msg.sender);
pickaxeNftCollection.safeTransferFrom(
playerPickaxe[msg.sender].value = _tokenId;
playerLastUpdate[msg.sender].isData = true;
function withdraw() external nonReentrant {
require(
playerPickaxe[msg.sender].isData,
"You do not have a pickaxe to withdraw."
);
uint256 reward = calculateRewards(msg.sender);
rewardsToken.transfer(msg.sender, reward);
pickaxeNftCollection.safeTransferFrom(
address(this),
msg.sender,
playerPickaxe[msg.sender].value,
1,
"Returning your old pickaxe"
);
playerPickaxe[msg.sender].isData = false;
playerLastUpdate[msg.sender].isData = true;
playerLastUpdate[msg.sender].value = block.timestamp;
}
function claim() external nonReentrant {
uint256 reward = calculateRewards(msg.sender);
rewardsToken.transfer(msg.sender, reward);
playerLastUpdate[msg.sender].isData = true;
playerLastUpdate[msg.sender].value = block.timestamp;
}
function calculateRewards(address _player)
public
view
returns (uint256 _rewards)
{
if (
!playerLastUpdate[_player].isData || !playerPickaxe[_player].isData
) {
return 0;
}
playerLastUpdate[_player].value;
100_000_000_000_000_000 *
(playerPickaxe[_player].value + 1);
}
function calculateRewards(address _player)
public
view
returns (uint256 _rewards)
{
if (
!playerLastUpdate[_player].isData || !playerPickaxe[_player].isData
) {
return 0;
}
playerLastUpdate[_player].value;
100_000_000_000_000_000 *
(playerPickaxe[_player].value + 1);
}
uint256 timeDifference = block.timestamp -
uint256 rewards = timeDifference *
return rewards;
} | 4,763,545 | [
1,
2257,
3134,
2795,
1308,
20092,
2674,
261,
41,
1460,
10895,
471,
3155,
13,
11417,
445,
358,
444,
326,
283,
6397,
1147,
471,
326,
423,
4464,
1849,
6138,
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
] | [
1,
1,
1,
1,
1,
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
] | [
1,
16351,
5444,
310,
353,
868,
8230,
12514,
16709,
16,
4232,
39,
2499,
2539,
6064,
288,
203,
565,
10895,
654,
39,
2499,
2539,
1071,
11732,
6002,
651,
73,
50,
1222,
2532,
31,
203,
565,
3155,
654,
39,
3462,
1071,
11732,
283,
6397,
1345,
31,
203,
203,
565,
3885,
12,
203,
3639,
10895,
654,
39,
2499,
2539,
6002,
651,
73,
8924,
1887,
16,
203,
3639,
3155,
654,
39,
3462,
314,
7424,
8924,
1887,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2499,
31,
203,
5666,
8787,
451,
6909,
4875,
17,
5206,
19,
16351,
87,
19,
3190,
94,
881,
84,
292,
267,
17,
12202,
2413,
19,
5471,
19,
654,
39,
2499,
2539,
19,
654,
39,
2499,
2539,
6064,
18,
18281,
14432,
203,
5666,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
7462,
19,
426,
8230,
12514,
16709,
18,
18281,
14432,
203,
565,
262,
288,
203,
3639,
6002,
651,
73,
50,
1222,
2532,
273,
6002,
651,
73,
8924,
1887,
31,
203,
3639,
283,
6397,
1345,
273,
314,
7424,
8924,
1887,
31,
203,
565,
289,
203,
203,
565,
1958,
1635,
620,
288,
203,
3639,
1426,
353,
751,
31,
203,
3639,
2254,
5034,
460,
31,
203,
565,
289,
203,
203,
203,
203,
565,
2874,
12,
2867,
516,
1635,
620,
13,
1071,
7291,
17968,
651,
73,
31,
203,
565,
2874,
12,
2867,
516,
1635,
620,
13,
1071,
7291,
3024,
1891,
31,
203,
565,
445,
384,
911,
12,
11890,
5034,
389,
2316,
548,
13,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
203,
5411,
6002,
2
] |
./full_match/5/0x551f08B4E4b1C9a4680715C1a468C998fA2C0d62/sources/C_/development/projects/quarkus-test/ContractPlattform/ContractPlattform/src/main/solidity/contract-platform.sol | overwrite the contract that should be removed with the last contract in array | function removeContract(uint indexOfContractToRemove) private {
if (indexOfContractToRemove != contractsOnPlatform.length-1) {
contractsOnPlatform[indexOfContractToRemove] = contractsOnPlatform[contractsOnPlatform.length-1];
}
}
The refund will cancel any offers. No commission will be charged.
This call will be only successful if certain conditions are met:
- only one party (buyer or developer) made a deposit so far -> instant refund
- the developer is late while the contract is in development
- both sides calling for refund, the refund will be done if the second party calls refund
| 1,895,684 | [
1,
19274,
326,
6835,
716,
1410,
506,
3723,
598,
326,
1142,
6835,
316,
526,
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,
1206,
8924,
12,
11890,
3133,
8924,
12765,
13,
3238,
288,
203,
3639,
309,
261,
31806,
8924,
12765,
480,
20092,
1398,
8201,
18,
2469,
17,
21,
13,
288,
203,
5411,
20092,
1398,
8201,
63,
31806,
8924,
12765,
65,
273,
20092,
1398,
8201,
63,
16351,
87,
1398,
8201,
18,
2469,
17,
21,
15533,
203,
3639,
289,
203,
565,
289,
203,
203,
3639,
1021,
16255,
903,
3755,
1281,
28641,
18,
2631,
1543,
19710,
903,
506,
1149,
2423,
18,
203,
3639,
1220,
745,
903,
506,
1338,
6873,
309,
8626,
4636,
854,
5100,
30,
203,
3639,
300,
1338,
1245,
18285,
261,
70,
16213,
578,
8751,
13,
7165,
279,
443,
1724,
1427,
10247,
317,
5934,
16255,
203,
3639,
300,
326,
8751,
353,
26374,
1323,
326,
6835,
353,
316,
17772,
203,
3639,
300,
3937,
22423,
4440,
364,
16255,
16,
326,
16255,
903,
506,
2731,
309,
326,
2205,
18285,
4097,
16255,
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
] |
/*
Copyright 2021 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.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol";
import { IExtension } from "../interfaces/IExtension.sol";
import { ISetToken } from "../interfaces/ISetToken.sol";
import { MutualUpgrade } from "../lib/MutualUpgrade.sol";
/**
* @title BaseManagerV2
* @author Set Protocol
*
* Smart contract manager that contains permissions and admin functionality. Implements IIP-64, supporting
* a registry of protected modules that can only be upgraded with methodologist consent.
*/
contract BaseManagerV2 is MutualUpgrade {
using Address for address;
using AddressArrayUtils for address[];
using SafeERC20 for IERC20;
/* ============ Struct ========== */
struct ProtectedModule {
bool isProtected; // Flag set to true if module is protected
address[] authorizedExtensionsList; // List of Extensions authorized to call module
mapping(address => bool) authorizedExtensions; // Map of extensions authorized to call module
}
/* ============ Events ============ */
event ExtensionAdded(
address _extension
);
event ExtensionRemoved(
address _extension
);
event MethodologistChanged(
address _oldMethodologist,
address _newMethodologist
);
event OperatorChanged(
address _oldOperator,
address _newOperator
);
event ExtensionAuthorized(
address _module,
address _extension
);
event ExtensionAuthorizationRevoked(
address _module,
address _extension
);
event ModuleProtected(
address _module,
address[] _extensions
);
event ModuleUnprotected(
address _module
);
event ReplacedProtectedModule(
address _oldModule,
address _newModule,
address[] _newExtensions
);
event EmergencyReplacedProtectedModule(
address _module,
address[] _extensions
);
event EmergencyRemovedProtectedModule(
address _module
);
event EmergencyResolved();
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == operator, "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == methodologist, "Must be methodologist");
_;
}
/**
* Throws if the sender is not a listed extension
*/
modifier onlyExtension() {
require(isExtension[msg.sender], "Must be extension");
_;
}
/**
* Throws if contract is in an emergency state following a unilateral operator removal of a
* protected module.
*/
modifier upgradesPermitted() {
require(emergencies == 0, "Upgrades paused by emergency");
_;
}
/**
* Throws if contract is *not* in an emergency state. Emergency replacement and resolution
* can only happen in an emergency
*/
modifier onlyEmergency() {
require(emergencies > 0, "Not in emergency");
_;
}
/* ============ State Variables ============ */
// Instance of SetToken
ISetToken public setToken;
// Array of listed extensions
address[] internal extensions;
// Mapping to check if extension is added
mapping(address => bool) public isExtension;
// Address of operator which typically executes manager only functions on Set Protocol modules
address public operator;
// Address of methodologist which serves as providing methodology for the index
address public methodologist;
// Counter incremented when the operator "emergency removes" a protected module. Decremented
// when methodologist executes an "emergency replacement". Operator can only add modules and
// extensions when `emergencies` is zero. Emergencies can only be declared "over" by mutual agreement
// between operator and methodologist or by the methodologist alone via `resolveEmergency`
uint256 public emergencies;
// Mapping of protected modules. These cannot be called or removed except by mutual upgrade.
mapping(address => ProtectedModule) public protectedModules;
// List of protected modules, for iteration. Used when checking that an extension removal
// can happen without methodologist approval
address[] public protectedModulesList;
// Boolean set when methodologist authorizes initialization after contract deployment.
// Must be true to call via `interactManager`.
bool public initialized;
/* ============ Constructor ============ */
constructor(
ISetToken _setToken,
address _operator,
address _methodologist
)
public
{
setToken = _setToken;
operator = _operator;
methodologist = _methodologist;
}
/* ============ External Functions ============ */
/**
* ONLY METHODOLOGIST : Called by the methodologist to enable contract. All `interactManager`
* calls revert until this is invoked. Lets methodologist review and authorize initial protected
* module settings.
*/
function authorizeInitialization() external onlyMethodologist {
require(!initialized, "Initialization authorized");
initialized = true;
}
/**
* MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newManager New manager address
*/
function setManager(address _newManager) external mutualUpgrade(operator, methodologist) {
require(_newManager != address(0), "Zero address not valid");
setToken.setManager(_newManager);
}
/**
* OPERATOR ONLY: Add a new extension that the BaseManager can call.
*
* @param _extension New extension to add
*/
function addExtension(address _extension) external upgradesPermitted onlyOperator {
require(!isExtension[_extension], "Extension already exists");
require(address(IExtension(_extension).manager()) == address(this), "Extension manager invalid");
_addExtension(_extension);
}
/**
* OPERATOR ONLY: Remove an existing extension tracked by the BaseManager.
*
* @param _extension Old extension to remove
*/
function removeExtension(address _extension) external onlyOperator {
require(isExtension[_extension], "Extension does not exist");
require(!_isAuthorizedExtension(_extension), "Extension used by protected module");
extensions.removeStorage(_extension);
isExtension[_extension] = false;
emit ExtensionRemoved(_extension);
}
/**
* MUTUAL UPGRADE: Authorizes an extension for a protected module. Operator and Methodologist must
* each call this function to execute the update. Adds extension to manager if not already present.
*
* @param _module Module to authorize extension for
* @param _extension Extension to authorize for module
*/
function authorizeExtension(address _module, address _extension)
external
mutualUpgrade(operator, methodologist)
{
require(protectedModules[_module].isProtected, "Module not protected");
require(!protectedModules[_module].authorizedExtensions[_extension], "Extension already authorized");
_authorizeExtension(_module, _extension);
emit ExtensionAuthorized(_module, _extension);
}
/**
* MUTUAL UPGRADE: Revokes extension authorization for a protected module. Operator and Methodologist
* must each call this function to execute the update. In order to remove the extension completely
* from the contract removeExtension must be called by the operator.
*
* @param _module Module to revoke extension authorization for
* @param _extension Extension to revoke authorization of
*/
function revokeExtensionAuthorization(address _module, address _extension)
external
mutualUpgrade(operator, methodologist)
{
require(protectedModules[_module].isProtected, "Module not protected");
require(isExtension[_extension], "Extension does not exist");
require(protectedModules[_module].authorizedExtensions[_extension], "Extension not authorized");
protectedModules[_module].authorizedExtensions[_extension] = false;
protectedModules[_module].authorizedExtensionsList.removeStorage(_extension);
emit ExtensionAuthorizationRevoked(_module, _extension);
}
/**
* ADAPTER ONLY: Interact with a module registered on the SetToken. Manager initialization must
* have been authorized by methodologist. Extension making this call must be authorized
* to call module if module is protected.
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/
function interactManager(address _module, bytes memory _data) external onlyExtension {
require(initialized, "Manager not initialized");
require(_module != address(setToken), "Extensions cannot call SetToken");
require(_senderAuthorizedForModule(_module, msg.sender), "Extension not authorized for module");
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
/**
* OPERATOR ONLY: Transfers _tokens held by the manager to _destination. Can be used to
* recover anything sent here accidentally. In BaseManagerV2, extensions should
* be the only contracts designated as `feeRecipient` in fee modules.
*
* @param _token ERC20 token to send
* @param _destination Address receiving the tokens
* @param _amount Quantity of tokens to send
*/
function transferTokens(address _token, address _destination, uint256 _amount) external onlyExtension {
IERC20(_token).safeTransfer(_destination, _amount);
}
/**
* OPERATOR ONLY: Add a new module to the SetToken.
*
* @param _module New module to add
*/
function addModule(address _module) external upgradesPermitted onlyOperator {
setToken.addModule(_module);
}
/**
* OPERATOR ONLY: Remove a new module from the SetToken. Any extensions associated with this
* module need to be removed in separate transactions via removeExtension.
*
* @param _module Module to remove
*/
function removeModule(address _module) external onlyOperator {
require(!protectedModules[_module].isProtected, "Module protected");
setToken.removeModule(_module);
}
/**
* OPERATOR ONLY: Marks a currently protected module as unprotected and deletes its authorized
* extension registries. Removes module from the SetToken. Increments the `emergencies` counter,
* prohibiting any operator-only module or extension additions until `emergencyReplaceProtectedModule`
* is executed or `resolveEmergency` is called by the methodologist.
*
* Called by operator when a module must be removed immediately for security reasons and it's unsafe
* to wait for a `mutualUpgrade` process to play out.
*
* NOTE: If removing a fee module, you can ensure all fees are distributed by calling distribute
* on the module's de-authorized fee extension after this call.
*
* @param _module Module to remove
*/
function emergencyRemoveProtectedModule(address _module) external onlyOperator {
_unProtectModule(_module);
setToken.removeModule(_module);
emergencies += 1;
emit EmergencyRemovedProtectedModule(_module);
}
/**
* OPERATOR ONLY: Marks an existing module as protected and authorizes extensions for
* it, adding them if necessary. Adds module to the protected modules list
*
* The operator uses this when they're adding new features and want to assure the methodologist
* they won't be unilaterally changed in the future. Cannot be called during an emergency because
* methodologist needs to explicitly approve protection arrangements under those conditions.
*
* NOTE: If adding a fee extension while protecting a fee module, it's important to set the
* module `feeRecipient` to the new extension's address (ideally before this call).
*
* @param _module Module to protect
* @param _extensions Array of extensions to authorize for protected module
*/
function protectModule(address _module, address[] memory _extensions)
external
upgradesPermitted
onlyOperator
{
require(setToken.getModules().contains(_module), "Module not added yet");
_protectModule(_module, _extensions);
emit ModuleProtected(_module, _extensions);
}
/**
* METHODOLOGIST ONLY: Marks a currently protected module as unprotected and deletes its authorized
* extension registries. Removes old module from the protected modules list.
*
* Called by the methodologist when they want to cede control over a protected module without triggering
* an emergency (for example, to remove it because its dead).
*
* @param _module Module to revoke protections for
*/
function unProtectModule(address _module) external onlyMethodologist {
_unProtectModule(_module);
emit ModuleUnprotected(_module);
}
/**
* MUTUAL UPGRADE: Replaces a protected module. Operator and Methodologist must each call this
* function to execute the update.
*
* > Marks a currently protected module as unprotected
* > Deletes its authorized extension registries.
* > Removes old module from SetToken.
* > Adds new module to SetToken.
* > Marks `_newModule` as protected and authorizes new extensions for it.
*
* Used when methodologists wants to guarantee that an existing protection arrangement is replaced
* with a suitable substitute (ex: upgrading a StreamingFeeSplitExtension).
*
* NOTE: If replacing a fee module, it's necessary to set the module `feeRecipient` to be
* the new fee extension address after this call. Any fees remaining in the old module's
* de-authorized extensions can be distributed by calling `distribute()` on the old extension.
*
* @param _oldModule Module to remove
* @param _newModule Module to add in place of removed module
* @param _newExtensions Extensions to authorize for new module
*/
function replaceProtectedModule(address _oldModule, address _newModule, address[] memory _newExtensions)
external
mutualUpgrade(operator, methodologist)
{
_unProtectModule(_oldModule);
setToken.removeModule(_oldModule);
setToken.addModule(_newModule);
_protectModule(_newModule, _newExtensions);
emit ReplacedProtectedModule(_oldModule, _newModule, _newExtensions);
}
/**
* MUTUAL UPGRADE & EMERGENCY ONLY: Replaces a module the operator has removed with
* `emergencyRemoveProtectedModule`. Operator and Methodologist must each call this function to
* execute the update.
*
* > Adds new module to SetToken.
* > Marks `_newModule` as protected and authorizes new extensions for it.
* > Adds `_newModule` to protectedModules list.
* > Decrements the emergencies counter,
*
* Used when methodologist wants to guarantee that a protection arrangement which was
* removed in an emergency is replaced with a suitable substitute. Operator's ability to add modules
* or extensions is restored after invoking this method (if this is the only emergency.)
*
* NOTE: If replacing a fee module, it's necessary to set the module `feeRecipient` to be
* the new fee extension address after this call. Any fees remaining in the old module's
* de-authorized extensions can be distributed by calling `accrueFeesAndDistribute` on the old extension.
*
* @param _module Module to add in place of removed module
* @param _extensions Array of extensions to authorize for replacement module
*/
function emergencyReplaceProtectedModule(
address _module,
address[] memory _extensions
)
external
mutualUpgrade(operator, methodologist)
onlyEmergency
{
setToken.addModule(_module);
_protectModule(_module, _extensions);
emergencies -= 1;
emit EmergencyReplacedProtectedModule(_module, _extensions);
}
/**
* METHODOLOGIST ONLY & EMERGENCY ONLY: Decrements the emergencies counter.
*
* Allows a methodologist to exit a state of emergency without replacing a protected module that
* was removed. This could happen if the module has no viable substitute or operator and methodologist
* agree that restoring normal operations is the best way forward.
*/
function resolveEmergency() external onlyMethodologist onlyEmergency {
emergencies -= 1;
emit EmergencyResolved();
}
/**
* METHODOLOGIST ONLY: Update the methodologist address
*
* @param _newMethodologist New methodologist address
*/
function setMethodologist(address _newMethodologist) external onlyMethodologist {
emit MethodologistChanged(methodologist, _newMethodologist);
methodologist = _newMethodologist;
}
/**
* OPERATOR ONLY: Update the operator address
*
* @param _newOperator New operator address
*/
function setOperator(address _newOperator) external onlyOperator {
emit OperatorChanged(operator, _newOperator);
operator = _newOperator;
}
/* ============ External Getters ============ */
function getExtensions() external view returns(address[] memory) {
return extensions;
}
function getAuthorizedExtensions(address _module) external view returns (address[] memory) {
return protectedModules[_module].authorizedExtensionsList;
}
function isAuthorizedExtension(address _module, address _extension) external view returns (bool) {
return protectedModules[_module].authorizedExtensions[_extension];
}
function getProtectedModules() external view returns (address[] memory) {
return protectedModulesList;
}
/* ============ Internal ============ */
/**
* Add a new extension that the BaseManager can call.
*/
function _addExtension(address _extension) internal {
extensions.push(_extension);
isExtension[_extension] = true;
emit ExtensionAdded(_extension);
}
/**
* Marks a currently protected module as unprotected and deletes it from authorized extension
* registries. Removes module from the SetToken.
*/
function _unProtectModule(address _module) internal {
require(protectedModules[_module].isProtected, "Module not protected");
// Clear mapping and array entries in struct before deleting mapping entry
for (uint256 i = 0; i < protectedModules[_module].authorizedExtensionsList.length; i++) {
address extension = protectedModules[_module].authorizedExtensionsList[i];
protectedModules[_module].authorizedExtensions[extension] = false;
}
delete protectedModules[_module];
protectedModulesList.removeStorage(_module);
}
/**
* Adds new module to SetToken. Marks `_newModule` as protected and authorizes
* new extensions for it. Adds `_newModule` module to protectedModules list.
*/
function _protectModule(address _module, address[] memory _extensions) internal {
require(!protectedModules[_module].isProtected, "Module already protected");
protectedModules[_module].isProtected = true;
protectedModulesList.push(_module);
for (uint i = 0; i < _extensions.length; i++) {
_authorizeExtension(_module, _extensions[i]);
}
}
/**
* Adds extension if not already added and marks extension as authorized for module
*/
function _authorizeExtension(address _module, address _extension) internal {
if (!isExtension[_extension]) {
_addExtension(_extension);
}
protectedModules[_module].authorizedExtensions[_extension] = true;
protectedModules[_module].authorizedExtensionsList.push(_extension);
}
/**
* Searches the extension mappings of each protected modules to determine if an extension
* is authorized by any of them. Authorized extensions cannot be unilaterally removed by
* the operator.
*/
function _isAuthorizedExtension(address _extension) internal view returns (bool) {
for (uint256 i = 0; i < protectedModulesList.length; i++) {
if (protectedModules[protectedModulesList[i]].authorizedExtensions[_extension]) {
return true;
}
}
return false;
}
/**
* Checks if `_sender` (an extension) is allowed to call a module (which may be protected)
*/
function _senderAuthorizedForModule(address _module, address _sender) internal view returns (bool) {
if (protectedModules[_module].isProtected) {
return protectedModules[_module].authorizedExtensions[_sender];
}
return true;
}
}
// 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);
}
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: 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");
}
}
}
/*
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;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*
* CHANGELOG:
* - 4/27/21: Added validatePairsWithArray methods
*/
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");
}
}
/*
Copyright 2021 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 { IBaseManager } from "./IBaseManager.sol";
interface IExtension {
function manager() external view returns (IBaseManager);
}
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken 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 SetToken
* @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);
}
/*
Copyright 2018 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.
*/
pragma solidity 0.6.10;
/**
* @title MutualUpgrade
* @author Set Protocol
*
* The MutualUpgrade contract contains a modifier for handling mutual upgrades between two parties
*/
contract MutualUpgrade {
/* ============ State Variables ============ */
// Mapping of upgradable units and if upgrade has been initialized by other party
mapping(bytes32 => bool) public mutualUpgrades;
/* ============ Events ============ */
event MutualUpgradeRegistered(
bytes32 _upgradeHash
);
/* ============ Modifiers ============ */
modifier mutualUpgrade(address _signerOne, address _signerTwo) {
require(
msg.sender == _signerOne || msg.sender == _signerTwo,
"Must be authorized address"
);
address nonCaller = _getNonCaller(_signerOne, _signerTwo);
// The upgrade hash is defined by the hash of the transaction call data and sender of msg,
// which uniquely identifies the function, arguments, and sender.
bytes32 expectedHash = keccak256(abi.encodePacked(msg.data, nonCaller));
if (!mutualUpgrades[expectedHash]) {
bytes32 newHash = keccak256(abi.encodePacked(msg.data, msg.sender));
mutualUpgrades[newHash] = true;
emit MutualUpgradeRegistered(newHash);
return;
}
delete mutualUpgrades[expectedHash];
// Run the rest of the upgrades
_;
}
/* ============ Internal Functions ============ */
function _getNonCaller(address _signerOne, address _signerTwo) internal view returns(address) {
return msg.sender == _signerOne ? _signerTwo : _signerOne;
}
}
// 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, 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;
}
}
/*
Copyright 2021 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.
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ISetToken } from "./ISetToken.sol";
interface IBaseManager {
function setToken() external returns(ISetToken);
function methodologist() external returns(address);
function operator() external returns(address);
function interactManager(address _module, bytes calldata _encoded) external;
function transferTokens(address _token, address _destination, uint256 _amount) external;
}
| * Throws if the sender is not a listed extension/ | modifier onlyExtension() {
require(isExtension[msg.sender], "Must be extension");
_;
}
| 280,431 | [
1,
21845,
309,
326,
5793,
353,
486,
279,
12889,
2710,
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,
9606,
1338,
3625,
1435,
288,
203,
3639,
2583,
12,
291,
3625,
63,
3576,
18,
15330,
6487,
315,
10136,
506,
2710,
8863,
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,
-100,
-100,
-100,
-100,
-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.17;
contract Lottery {
address public manager;
address[] public players;
//constructor () public {
// manager=msg.sender;
//}
function Lottery() public {
manager=msg.sender;
}
modifier onlyManagerCanCall() {
require(msg.sender==manager);//only manager can pickWinner
_;
}
function getManager() public view returns (address) {
return manager;
}
//投注彩票
function enter() public payable {
require(msg.value==1 ether);//assure cost money
players.push(msg.sender);
}
function getAllPlayers() public view returns (address[]) {
return players;
}
function getBalance() public view returns(uint) {
return this.balance;
}
function getPlayersCount() public view returns(uint) {
return players.length;
}
function random() private view returns(uint) {
return uint(keccak256(block.difficulty,now,players));
}
function pickWinner() public onlyManagerCanCall returns(address) {
uint index=random()%players.length;
address winner=players[index];
winner.transfer(this.balance);
players = new address[](0);//clear players[]
return winner;
}
function refund() public onlyManagerCanCall {
//require(msg.sender==manager);
for(uint i=0;i<players.length;i++) {
players[i].transfer(1 ether);
}
players = new address[](0);//clear players[]
}
}
| require(msg.sender==manager); | function refund() public onlyManagerCanCall {
for(uint i=0;i<players.length;i++) {
players[i].transfer(1 ether);
}
}
| 6,470,854 | [
1,
6528,
12,
3576,
18,
15330,
631,
4181,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16255,
1435,
1071,
1338,
1318,
2568,
1477,
288,
203,
3639,
364,
12,
11890,
277,
33,
20,
31,
77,
32,
1601,
414,
18,
2469,
31,
77,
27245,
288,
203,
5411,
18115,
63,
77,
8009,
13866,
12,
21,
225,
2437,
1769,
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
] |
./partial_match/80001/0xC06E18d4Ce6b1b0f20Bad77FBFF7C0F7BabbC01F/sources/GAME_NFT.sol | @notice You can link client account A to Crypto account Z even @notice call this with account(0) to un-link @param game_ - the # of the game which holds this account @param inGameAccount_ - the in-game account Id controlled by the game @param cryptoAccount_ - the Ethereum account Id of the user | function approveCryptoAccount(uint game_, bytes32 inGameAccount_, address cryptoAccount_)
external
operatorOrMinion(game_)
{
require(gameToCrypto[game_][inGameAccount_] == address(0), "client must not already be linked");
approvedCryptoAccounts[game_][inGameAccount_] = cryptoAccount_;
emit AccountApproved(game_, inGameAccount_, cryptoAccount_);
}
| 8,818,178 | [
1,
6225,
848,
1692,
1004,
2236,
432,
358,
15629,
2236,
2285,
5456,
225,
745,
333,
598,
2236,
12,
20,
13,
358,
640,
17,
1232,
225,
7920,
67,
300,
326,
225,
434,
326,
7920,
1492,
14798,
333,
2236,
225,
316,
12496,
3032,
67,
300,
326,
316,
17,
13957,
2236,
3124,
25934,
635,
326,
7920,
225,
8170,
3032,
67,
300,
326,
512,
18664,
379,
2236,
3124,
434,
326,
729,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
6617,
537,
18048,
3032,
12,
11890,
7920,
67,
16,
1731,
1578,
316,
12496,
3032,
67,
16,
1758,
8170,
3032,
67,
13,
203,
565,
3903,
203,
565,
3726,
1162,
2930,
285,
12,
13957,
67,
13,
203,
225,
288,
203,
565,
2583,
12,
13957,
774,
18048,
63,
13957,
67,
6362,
267,
12496,
3032,
67,
65,
422,
1758,
12,
20,
3631,
315,
2625,
1297,
486,
1818,
506,
8459,
8863,
203,
565,
20412,
18048,
13971,
63,
13957,
67,
6362,
267,
12496,
3032,
67,
65,
273,
8170,
3032,
67,
31,
203,
565,
3626,
6590,
31639,
12,
13957,
67,
16,
316,
12496,
3032,
67,
16,
8170,
3032,
67,
1769,
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
] |
// SPDX-License-Identifier: MIT-open-group
pragma solidity ^0.8.11;
library ETHDKGErrorCodes {
// ETHDKG error codes
bytes32 public constant ETHDKG_ONLY_VALIDATORS_ALLOWED = "100"; //"ETHDKG: Only validators allowed!"
bytes32 public constant ETHDKG_VARIABLE_CANNOT_BE_SET_WHILE_RUNNING = "101"; //"ETHDKG: This variable cannot be set if an ETHDKG round is running!"
bytes32 public constant ETHDKG_MIN_VALIDATORS_NOT_MET = "102"; //"ETHDKG: Minimum number of validators staked not met!"
bytes32 public constant ETHDKG_NOT_IN_POST_REGISTRATION_PHASE = "103"; //"ETHDKG: should be in post-registration accusation phase!"
bytes32 public constant ETHDKG_ACCUSED_NOT_VALIDATOR = "104"; //"ETHDKG: Dispute Failed! Dishonest Address is not a validator at the moment!"
bytes32 public constant ETHDKG_ACCUSED_PARTICIPATING_IN_ROUND = "105"; //"ETHDKG: Dispute failed! dishonestParticipant is participating in this ETHDKG round!"
bytes32 public constant ETHDKG_NOT_IN_POST_SHARED_DISTRIBUTION_PHASE = "106"; // "ETHDKG: should be in post-ShareDistribution accusation phase!"
bytes32 public constant ETHDKG_ACCUSED_NOT_PARTICIPATING_IN_ROUND = "107"; //"ETHDKG: Dispute failed! Dishonest Participant is not participating in this ETHDKG round!"
bytes32 public constant ETHDKG_ACCUSED_DISTRIBUTED_SHARES_IN_ROUND = "108"; //"ETHDKG: Dispute failed! Supposed dishonest participant distributed its share in this ETHDKG round!"
bytes32 public constant ETHDKG_ACCUSED_HAS_COMMITMENTS = "109"; //"ETHDKG: Dispute failed! It looks like the supposed dishonest participant had commitments! "
bytes32 public constant ETHDKG_NOT_IN_DISPUTE_PHASE = "110"; // "ETHDKG: Dispute failed! Contract is not in dispute phase!"
bytes32 public constant ETHDKG_DISPUTER_NOT_PARTICIPATING_IN_ROUND = "111"; // "ETHDKG: Dispute failed! Disputer is not participating in this ETHDKG round!"
bytes32 public constant ETHDKG_ACCUSED_DID_NOT_DISTRIBUTE_SHARES_IN_ROUND = "112"; // "ETHDKG: Dispute failed! dishonestParticipant did not distribute shares!"
bytes32 public constant ETHDKG_DISPUTER_DID_NOT_DISTRIBUTE_SHARES_IN_ROUND = "113"; // "ETHDKG: Dispute failed! Disputer did not distribute shares!"
bytes32 public constant ETHDKG_SHARES_AND_COMMITMENTS_MISMATCH = "114"; // "ETHDKG: Dispute failed! Submitted commitments and encrypted shares don't match!"
bytes32 public constant ETHDKG_INVALID_KEY_OR_PROOF = "115"; // "ETHDKG: Dispute failed! Invalid shared key or proof!"
bytes32 public constant ETHDKG_NOT_IN_POST_KEYSHARE_SUBMISSION_PHASE = "116"; // "ETHDKG: Dispute failed! Should be in post-KeyShareSubmission phase!"
bytes32 public constant ETHDKG_ACCUSED_SUBMITTED_SHARES_IN_ROUND = "117"; // "ETHDKG: Dispute failed! Dishonest participant submitted its key shares in this ETHDKG round!"
bytes32 public constant ETHDKG_NOT_IN_POST_GPKJ_SUBMISSION_PHASE = "118"; // "ETHDKG: Dispute Failed! Should be in post-GPKJSubmission phase!"
bytes32 public constant ETHDKG_ACCUSED_DID_NOT_PARTICIPATE_IN_GPKJ_SUBMISSION = "120"; // "ETHDKG: Dispute failed! Dishonest participant did participate in this GPKj submission!"
bytes32 public constant ETHDKG_ACCUSED_DISTRIBUTED_GPKJ = "121"; // "ETHDKG: Dispute failed! It looks like the dishonestParticipant distributed its GPKJ!"
bytes32 public constant ETHDKG_ACCUSED_DID_NOT_SUBMIT_GPKJ_IN_ROUND = "122"; // "ETHDKG: Dispute Failed! Dishonest participant didn't submit his GPKJ for this round!"
bytes32 public constant ETHDKG_DISPUTER_DID_NOT_SUBMIT_GPKJ_IN_ROUND = "123"; // "ETHDKG: Dispute Failed! Disputer didn't submit his GPKJ for this round!"
bytes32 public constant ETHDKG_INVALID_ARGS = "124"; // "ETHDKG: Dispute Failed! Invalid submission of arguments!"
bytes32 public constant ETHDKG_INVALID_COMMITMENTS = "125"; // "ETHDKG: Dispute Failed! Invalid number of commitments provided!"
bytes32 public constant ETHDKG_INVALID_OR_DUPLICATED_PARTICIPANT = "126"; // "ETHDKG: Dispute Failed! Invalid or duplicated participant address!"
bytes32 public constant ETHDKG_INVALID_SHARES_OR_COMMITMENTS = "127"; // "ETHDKG: Dispute Failed! Invalid shares or commitments!"
bytes32 public constant ETHDKG_NOT_IN_REGISTRATION_PHASE = "128"; // "ETHDKG: Cannot register at the moment"
bytes32 public constant ETHDKG_PUBLIC_KEY_ZERO = "130"; // "ETHDKG: Registration failed - pubKey should be different from 0!"
bytes32 public constant ETHDKG_PUBLIC_KEY_NOT_ON_CURVE = "131"; // "ETHDKG: Registration failed - public key not on elliptic curve!"
bytes32 public constant ETHDKG_PARTICIPANT_PARTICIPATING_IN_ROUND = "132"; // "ETHDKG: Participant is already participating in this ETHDKG round!"
bytes32 public constant ETHDKG_NOT_IN_SHARED_DISTRIBUTION_PHASE = "133"; // "ETHDKG: cannot participate on this phase"
bytes32 public constant ETHDKG_INVALID_NONCE = "134"; // "ETHDKG: Share distribution failed, participant with invalid nonce!"
bytes32 public constant ETHDKG_PARTICIPANT_DISTRIBUTED_SHARES_IN_ROUND = "135"; // "ETHDKG: Participant already distributed shares this ETHDKG round!"
bytes32 public constant ETHDKG_INVALID_NUM_ENCRYPTED_SHARES = "136"; // "ETHDKG: Share distribution failed - invalid number of encrypted shares provided!"
bytes32 public constant ETHDKG_INVALID_NUM_COMMITMENTS = "137"; // "ETHDKG: Key sharing failed - invalid number of commitments provided!"
bytes32 public constant ETHDKG_COMMITMENT_NOT_ON_CURVE = "138"; // "ETHDKG: Key sharing failed - commitment not on elliptic curve!"
bytes32 public constant ETHDKG_COMMITMENT_ZERO = "138"; // "ETHDKG: Commitments shouldn't be 0!"
bytes32 public constant ETHDKG_DISTRIBUTED_SHARE_HASH_ZERO = "139"; // "ETHDKG: The hash of encryptedShares and commitments should be different from 0!"
bytes32 public constant ETHDKG_NOT_IN_KEYSHARE_SUBMISSION_PHASE = "140"; // "ETHDKG: cannot participate on key share submission phase"
bytes32 public constant ETHDKG_PARTICIPANT_SUBMITTED_KEYSHARES_IN_ROUND = "141"; // "ETHDKG: Participant already submitted key shares this ETHDKG round!"
bytes32 public constant ETHDKG_INVALID_KEYSHARE_G1 = "141"; //"ETHDKG: Key share submission failed - invalid key share G1!"
bytes32 public constant ETHDKG_INVALID_KEYSHARE_G2 = "142"; //"ETHDKG: Key share submission failed - invalid key share G2!"
bytes32 public constant ETHDKG_NOT_IN_MASTER_PUBLIC_KEY_SUBMISSION_PHASE = "143"; // "ETHDKG: cannot participate on master public key submission phase"
bytes32 public constant ETHDKG_MASTER_PUBLIC_KEY_PAIRING_CHECK_FAILURE = "144"; // "ETHDKG: Master key submission pairing check failed!"
bytes32 public constant ETHDKG_NOT_IN_GPKJ_SUBMISSION_PHASE = "145"; // "ETHDKG: Not in GPKJ submission phase"
bytes32 public constant ETHDKG_PARTICIPANT_SUBMITTED_GPKJ_IN_ROUND = "146"; // "ETHDKG: Participant already submitted GPKj this ETHDKG round!"
bytes32 public constant ETHDKG_GPKJ_ZERO = "147"; // "ETHDKG: GPKj cannot be all zeros!"
bytes32 public constant ETHDKG_NOT_IN_POST_GPKJ_DISPUTE_PHASE = "148"; // "ETHDKG: should be in post-GPKJDispute phase!"
bytes32 public constant ETHDKG_REQUISITES_INCOMPLETE = "149"; // "ETHDKG: Not all requisites to complete this ETHDKG round were completed!"
bytes32 public constant ETHDKG_KEYSHARE_PHASE_INVALID_NONCE = "150"; // "ETHDKG: Key share submission failed, participant with invalid nonce!"
bytes32 public constant ETHDKG_MIGRATION_INVALID_NONCE = "151"; // "ETHDKG: Only can execute this with nonce 0!"
bytes32 public constant ETHDKG_MIGRATION_INPUT_DATA_MISMATCH = "152"; // "ETHDKG: All input data length should match!"
}
| "ETHDKG: Dispute Failed! Dishonest participant didn't submit his GPKJ for this round!"
| bytes32 public constant ETHDKG_ACCUSED_DID_NOT_SUBMIT_GPKJ_IN_ROUND = "122"; | 12,560,432 | [
1,
6,
1584,
44,
3398,
43,
30,
3035,
2507,
11175,
5,
463,
1468,
265,
395,
14188,
10242,
1404,
4879,
18423,
4948,
47,
46,
364,
333,
3643,
4442,
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,
565,
1731,
1578,
1071,
5381,
512,
2455,
3398,
43,
67,
31414,
20093,
67,
40,
734,
67,
4400,
67,
8362,
6068,
67,
43,
8784,
46,
67,
706,
67,
15092,
273,
315,
22266,
14432,
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
] |
/**
* The Consumer Contract Wallet
* Copyright (C) 2018 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.25;
/// @title The Controller interface provides access to an external list of controllers.
interface IController {
function isController(address) external view returns (bool);
}
/// @title Controller stores a list of controller addresses that can be used for authentication in other contracts.
contract Controller is IController {
event AddedController(address _sender, address _controller);
event RemovedController(address _sender, address _controller);
mapping (address => bool) private _isController;
uint private _controllerCount;
/// @dev Constructor initializes the list of controllers with the provided address.
/// @param _account address to add to the list of controllers.
constructor(address _account) public {
_addController(_account);
}
/// @dev Checks if message sender is a controller.
modifier onlyController() {
require(isController(msg.sender), "sender is not a controller");
_;
}
/// @dev Add a new controller to the list of controllers.
/// @param _account address to add to the list of controllers.
function addController(address _account) external onlyController {
_addController(_account);
}
/// @dev Remove a controller from the list of controllers.
/// @param _account address to remove from the list of controllers.
function removeController(address _account) external onlyController {
_removeController(_account);
}
/// @return true if the provided account is a controller.
function isController(address _account) public view returns (bool) {
return _isController[_account];
}
/// @return the current number of controllers.
function controllerCount() public view returns (uint) {
return _controllerCount;
}
/// @dev Internal-only function that adds a new controller.
function _addController(address _account) internal {
require(!_isController[_account], "provided account is already a controller");
_isController[_account] = true;
_controllerCount++;
emit AddedController(msg.sender, _account);
}
/// @dev Internal-only function that removes an existing controller.
function _removeController(address _account) internal {
require(_isController[_account], "provided account is not a controller");
require(_controllerCount > 1, "cannot remove the last controller");
_isController[_account] = false;
_controllerCount--;
emit RemovedController(msg.sender, _account);
}
}
/**
* BSD 2-Clause License
*
* Copyright (c) 2018, True Names Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
interface ENS {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public;
function setResolver(bytes32 node, address resolver) public;
function setOwner(bytes32 node, address owner) public;
function setTTL(bytes32 node, uint64 ttl) public;
function owner(bytes32 node) public view returns (address);
function resolver(bytes32 node) public view returns (address);
function ttl(bytes32 node) public view returns (uint64);
}
/// @title Resolver returns the controller contract address.
interface IResolver {
function addr(bytes32) external view returns (address);
}
/// @title Controllable implements access control functionality based on a controller set in ENS.
contract Controllable {
/// @dev _ENS points to the ENS registry smart contract.
ENS private _ENS;
/// @dev Is the registered ENS name of the controller contract.
bytes32 private _node;
/// @dev Constructor initializes the controller contract object.
/// @param _ens is the address of the ENS.
/// @param _controllerName is the ENS name of the Controller.
constructor(address _ens, bytes32 _controllerName) internal {
_ENS = ENS(_ens);
_node = _controllerName;
}
/// @dev Checks if message sender is the controller.
modifier onlyController() {
require(_isController(msg.sender), "sender is not a controller");
_;
}
/// @return true if the provided account is the controller.
function _isController(address _account) internal view returns (bool) {
return IController(IResolver(_ENS.resolver(_node)).addr(_node)).isController(_account);
}
}
/// @title Date provides date parsing functionality.
contract Date {
bytes32 constant private JANUARY = keccak256("Jan");
bytes32 constant private FEBRUARY = keccak256("Feb");
bytes32 constant private MARCH = keccak256("Mar");
bytes32 constant private APRIL = keccak256("Apr");
bytes32 constant private MAY = keccak256("May");
bytes32 constant private JUNE = keccak256("Jun");
bytes32 constant private JULY = keccak256("Jul");
bytes32 constant private AUGUST = keccak256("Aug");
bytes32 constant private SEPTEMBER = keccak256("Sep");
bytes32 constant private OCTOBER = keccak256("Oct");
bytes32 constant private NOVEMBER = keccak256("Nov");
bytes32 constant private DECEMBER = keccak256("Dec");
/// @return the number of the month based on its name.
/// @param _month the first three letters of a month's name e.g. "Jan".
function _monthToNumber(string _month) internal pure returns (uint8) {
bytes32 month = keccak256(abi.encodePacked(_month));
if (month == JANUARY) {
return 1;
} else if (month == FEBRUARY) {
return 2;
} else if (month == MARCH) {
return 3;
} else if (month == APRIL) {
return 4;
} else if (month == MAY) {
return 5;
} else if (month == JUNE) {
return 6;
} else if (month == JULY) {
return 7;
} else if (month == AUGUST) {
return 8;
} else if (month == SEPTEMBER) {
return 9;
} else if (month == OCTOBER) {
return 10;
} else if (month == NOVEMBER) {
return 11;
} else if (month == DECEMBER) {
return 12;
} else {
revert("not a valid month");
}
}
}
// <ORACLIZE_API>
// Release targetted at solc 0.4.25 to silence compiler warning/error messages, compatible down to 0.4.22
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// This api is currently targeted at 0.4.22 to 0.4.25 (stable builds), please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
pragma solidity >=0.4.22;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal pure {
uint capacity = _capacity;
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + buffer length + sizeof(buffer length)
dest := add(add(bufptr, buflen), 32)
// Update buffer length
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
// Update buffer length
mstore(bufptr, add(buflen, 1))
}
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
// Following should never be reached with a preceding return, however
// this is just a placeholder function, ideally meant to be defined in
// child contract when proofs are used
myid; result; proof; // Silence compiler warnings
oraclize = OraclizeI(0); // Additional compiler silence about making function pure/view.
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) view internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
// the following variables can be relaxed
// check relaxed random contract under ethereum-examples repo
// for an idea on how to override and replace comit hash vars
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(context_name, queryId)))))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
// </ORACLIZE_API>
/// @title JSON provides JSON parsing functionality.
contract JSON is usingOraclize{
using strings for *;
bytes32 constant private prefixHash = keccak256("{\"ETH\":");
/// @dev Extracts JSON rate value from the response object.
/// @param _json body of the JSON response from the CryptoCompare API.
function parseRate(string _json) public pure returns (string) {
uint json_len = abi.encodePacked(_json).length;
//{"ETH":}.length = 8, assuming a (maximum of) 18 digit prevision
require(json_len > 8 && json_len <= 28, "misformatted input");
bytes memory jsonPrefix = new bytes(7);
copyBytes(abi.encodePacked(_json), 0, 7, jsonPrefix, 0);
require(keccak256(jsonPrefix) == prefixHash, "prefix mismatch");
strings.slice memory body = _json.toSlice();
body.split(":".toSlice()); //we are sure that ':' is included in the string, body now contains the rate+'}'
json_len = body._len;
body.until("}".toSlice());
require(body._len == json_len-1,"not json format"); //ensure that the json is properly terminated with a '}'
return body.toString();
}
}
/// @title ParseIntScientific provides floating point in scientific notation (e.g. e-5) parsing functionality.
contract ParseIntScientific {
using SafeMath for uint256;
byte constant private PLUS_ASCII = byte(43); //decimal value of '+'
byte constant private DASH_ASCII = byte(45); //decimal value of '-'
byte constant private DOT_ASCII = byte(46); //decimal value of '.'
byte constant private ZERO_ASCII = byte(48); //decimal value of '0'
byte constant private NINE_ASCII = byte(57); //decimal value of '9'
byte constant private E_ASCII = byte(69); //decimal value of 'E'
byte constant private e_ASCII = byte(101); //decimal value of 'e'
/// @dev ParseIntScientific delegates the call to _parseIntScientific(string, uint) with the 2nd argument being 0.
function _parseIntScientific(string _inString) internal pure returns (uint) {
return _parseIntScientific(_inString, 0);
}
/// @dev ParseIntScientificWei parses a rate expressed in ETH and returns its wei denomination
function _parseIntScientificWei(string _inString) internal pure returns (uint) {
return _parseIntScientific(_inString, 18);
}
/// @dev ParseIntScientific parses a JSON standard - floating point number.
/// @param _inString is input string.
/// @param _magnitudeMult multiplies the number with 10^_magnitudeMult.
function _parseIntScientific(string _inString, uint _magnitudeMult) internal pure returns (uint) {
bytes memory inBytes = bytes(_inString);
uint mint = 0; // the final uint returned
uint mintDec = 0; // the uint following the decimal point
uint mintExp = 0; // the exponent
uint decMinted = 0; // how many decimals were 'minted'.
uint expIndex = 0; // the position in the byte array that 'e' was found (if found)
bool integral = false; // indicates the existence of the integral part, it should always exist (even if 0) e.g. 'e+1' or '.1' is not valid
bool decimals = false; // indicates a decimal number, set to true if '.' is found
bool exp = false; // indicates if the number being parsed has an exponential representation
bool minus = false; // indicated if the exponent is negative
bool plus = false; // indicated if the exponent is positive
for (uint i = 0; i < inBytes.length; i++) {
if ((inBytes[i] >= ZERO_ASCII) && (inBytes[i] <= NINE_ASCII) && (!exp)) {
// 'e' not encountered yet, minting integer part or decimals
if (decimals) {
// '.' encountered
//use safeMath in case there is an overflow
mintDec = mintDec.mul(10);
mintDec = mintDec.add(uint(inBytes[i]) - uint(ZERO_ASCII));
decMinted++; //keep track of the #decimals
} else {
// integral part (before '.')
integral = true;
//use safeMath in case there is an overflow
mint = mint.mul(10);
mint = mint.add(uint(inBytes[i]) - uint(ZERO_ASCII));
}
} else if ((inBytes[i] >= ZERO_ASCII) && (inBytes[i] <= NINE_ASCII) && (exp)) {
//exponential notation (e-/+) has been detected, mint the exponent
mintExp = mintExp.mul(10);
mintExp = mintExp.add(uint(inBytes[i]) - uint(ZERO_ASCII));
} else if (inBytes[i] == DOT_ASCII) {
//an integral part before should always exist before '.'
require(integral, "missing integral part");
// an extra decimal point makes the format invalid
require(!decimals, "duplicate decimal point");
//the decimal point should always be before the exponent
require(!exp, "decimal after exponent");
decimals = true;
} else if (inBytes[i] == DASH_ASCII) {
// an extra '-' should be considered an invalid character
require(!minus, "duplicate -");
require(!plus, "extra sign");
require(expIndex + 1 == i, "- sign not immediately after e");
minus = true;
} else if (inBytes[i] == PLUS_ASCII) {
// an extra '+' should be considered an invalid character
require(!plus, "duplicate +");
require(!minus, "extra sign");
require(expIndex + 1 == i, "+ sign not immediately after e");
plus = true;
} else if ((inBytes[i] == E_ASCII) || (inBytes[i] == e_ASCII)) {
//an integral part before should always exist before 'e'
require(integral, "missing integral part");
// an extra 'e' or 'E' should be considered an invalid character
require(!exp, "duplicate exponent symbol");
exp = true;
expIndex = i;
} else {
revert("invalid digit");
}
}
if (minus || plus) {
// end of string e[x|-] without specifying the exponent
require(i > expIndex + 2);
} else if (exp) {
// end of string (e) without specifying the exponent
require(i > expIndex + 1);
}
if (minus) {
// e^(-x)
if (mintExp >= _magnitudeMult) {
// the (negative) exponent is bigger than the given parameter for "shifting left".
// use integer division to reduce the precision.
require(mintExp - _magnitudeMult < 78, "exponent > 77"); //
mint /= 10 ** (mintExp - _magnitudeMult);
return mint;
} else {
// the (negative) exponent is smaller than the given parameter for "shifting left".
//no need for underflow check
_magnitudeMult = _magnitudeMult - mintExp;
}
} else {
// e^(+x), positive exponent or no exponent
// just shift left as many times as indicated by the exponent and the shift parameter
_magnitudeMult = _magnitudeMult.add(mintExp);
}
if (_magnitudeMult >= decMinted) {
// the decimals are fewer or equal than the shifts: use all of them
// shift number and add the decimals at the end
// include decimals if present in the original input
require(decMinted < 78, "more than 77 decimal digits parsed"); //
mint = mint.mul(10 ** (decMinted));
mint = mint.add(mintDec);
//// add zeros at the end if the decimals were fewer than #_magnitudeMult
require(_magnitudeMult - decMinted < 78, "exponent > 77"); //
mint = mint.mul(10 ** (_magnitudeMult - decMinted));
} else {
// the decimals are more than the #_magnitudeMult shifts
// use only the ones needed, discard the rest
decMinted -= _magnitudeMult;
require(decMinted < 78, "more than 77 decimal digits parsed"); //
mintDec /= 10 ** (decMinted);
// shift number and add the decimals at the end
require(_magnitudeMult < 78, "more than 77 decimal digits parsed"); //
mint = mint.mul(10 ** (_magnitudeMult));
mint = mint.add(mintDec);
}
return mint;
}
}
/*
* Copyright 2016 Nick Johnson
*
* 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.
*/
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (self & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (self & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (self & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (self & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (self & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
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;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 Smart Contract Solutions, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @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;
}
}
/**
* This method was modified from the GPLv3 solidity code found in this repository
* https://github.com/vcealicu/melonport-price-feed/blob/master/pricefeed/PriceFeed.sol
*/
/// @title Base64 provides base 64 decoding functionality.
contract Base64 {
bytes constant BASE64_DECODE_CHAR = hex"000000000000000000000000000000000000000000000000000000000000000000000000000000000000003e003e003f3435363738393a3b3c3d00000000000000000102030405060708090a0b0c0d0e0f10111213141516171819000000003f001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233";
/// @return decoded array of bytes.
/// @param _encoded base 64 encoded array of bytes.
function _base64decode(bytes _encoded) internal pure returns (bytes) {
byte v1;
byte v2;
byte v3;
byte v4;
uint length = _encoded.length;
bytes memory result = new bytes(length);
uint index;
// base64 encoded strings can't be length 0 and they must be divisble by 4
require(length > 0 && length % 4 == 0, "invalid base64 encoding");
if (keccak256(abi.encodePacked(_encoded[length - 2])) == keccak256("=")) {
length -= 2;
} else if (keccak256(abi.encodePacked(_encoded[length - 1])) == keccak256("=")) {
length -= 1;
}
uint count = length >> 2 << 2;
for (uint i = 0; i < count;) {
v1 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
v2 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
v3 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
v4 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
result[index++] = (v1 << 2 | v2 >> 4) & 255;
result[index++] = (v2 << 4 | v3 >> 2) & 255;
result[index++] = (v3 << 6 | v4) & 255;
}
if (length - count == 2) {
v1 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
v2 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
result[index++] = (v1 << 2 | v2 >> 4) & 255;
} else if (length - count == 3) {
v1 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
v2 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
v3 = BASE64_DECODE_CHAR[uint(_encoded[i++])];
result[index++] = (v1 << 2 | v2 >> 4) & 255;
result[index++] = (v2 << 4 | v3 >> 2) & 255;
}
// Set to correct length.
assembly {
mstore(result, index)
}
return result;
}
}
/// @title Oracle converts ERC20 token amounts into equivalent ether amounts based on cryptocurrency exchange rates.
interface IOracle {
function convert(address, uint) external view returns (bool, uint);
}
/// @title Oracle provides asset exchange rates and conversion functionality.
contract Oracle is usingOraclize, Base64, Date, JSON, Controllable, ParseIntScientific, IOracle {
using strings for *;
using SafeMath for uint256;
/*******************/
/* Events */
/*****************/
event AddedToken(address _sender, address _token, string _symbol, uint _magnitude);
event RemovedToken(address _sender, address _token);
event UpdatedTokenRate(address _sender, address _token, uint _rate);
event SetGasPrice(address _sender, uint _gasPrice);
event Converted(address _sender, address _token, uint _amount, uint _ether);
event RequestedUpdate(string _symbol);
event FailedUpdateRequest(string _reason);
event VerifiedProof(bytes _publicKey, string _result);
event SetCryptoComparePublicKey(address _sender, bytes _publicKey);
/**********************/
/* Constants */
/********************/
uint constant private PROOF_LEN = 165;
uint constant private ECDSA_SIG_LEN = 65;
uint constant private ENCODING_BYTES = 2;
uint constant private HEADERS_LEN = PROOF_LEN - 2 * ENCODING_BYTES - ECDSA_SIG_LEN; // 2 bytes encoding headers length + 2 for signature.
uint constant private DIGEST_BASE64_LEN = 44; //base64 encoding of the SHA256 hash (32-bytes) of the result: fixed length.
uint constant private DIGEST_OFFSET = HEADERS_LEN - DIGEST_BASE64_LEN; // the starting position of the result hash in the headers string.
uint constant private MAX_BYTE_SIZE = 256; //for calculating length encoding
struct Token {
string symbol; // Token symbol
uint magnitude; // 10^decimals
uint rate; // Token exchange rate in wei
uint lastUpdate; // Time of the last rate update
bool exists; // Flags if the struct is empty or not
}
mapping(address => Token) public tokens;
address[] private _tokenAddresses;
bytes public APIPublicKey;
mapping(bytes32 => address) private _queryToToken;
/// @dev Construct the oracle with multiple controllers, address resolver and custom gas price.
/// @dev _resolver is the oraclize address resolver contract address.
/// @param _ens is the address of the ENS.
/// @param _controllerName is the ENS name of the Controller.
constructor(address _resolver, address _ens, bytes32 _controllerName) Controllable(_ens, _controllerName) public {
APIPublicKey = hex"a0f4f688350018ad1b9785991c0bde5f704b005dc79972b114dbed4a615a983710bfc647ebe5a320daa28771dce6a2d104f5efa2e4a85ba3760b76d46f8571ca";
OAR = OraclizeAddrResolverI(_resolver);
oraclize_setCustomGasPrice(10000000000);
oraclize_setProof(proofType_Native);
}
/// @dev Updates the Crypto Compare public API key.
function updateAPIPublicKey(bytes _publicKey) external onlyController {
APIPublicKey = _publicKey;
emit SetCryptoComparePublicKey(msg.sender, _publicKey);
}
/// @dev Sets the gas price used by oraclize query.
function setCustomGasPrice(uint _gasPrice) external onlyController {
oraclize_setCustomGasPrice(_gasPrice);
emit SetGasPrice(msg.sender, _gasPrice);
}
/// @dev Convert ERC20 token amount to the corresponding ether amount (used by the wallet contract).
/// @param _token ERC20 token contract address.
/// @param _amount amount of token in base units.
function convert(address _token, uint _amount) external view returns (bool, uint) {
// Store the token in memory to save map entry lookup gas.
Token storage token = tokens[_token];
// If the token exists require that its rate is not zero
if (token.exists) {
require(token.rate != 0, "token rate is 0");
// Safely convert the token amount to ether based on the exchange rate.
// return the value and a 'true' implying that the token is protected
return (true, _amount.mul(token.rate).div(token.magnitude));
}
// this returns a 'false' to imply that a card is not protected
return (false, 0);
}
/// @dev Add ERC20 tokens to the list of supported tokens.
/// @param _tokens ERC20 token contract addresses.
/// @param _symbols ERC20 token names.
/// @param _magnitude 10 to the power of number of decimal places used by each ERC20 token.
/// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.
function addTokens(address[] _tokens, bytes32[] _symbols, uint[] _magnitude, uint _updateDate) external onlyController {
// Require that all parameters have the same length.
require(_tokens.length == _symbols.length && _tokens.length == _magnitude.length, "parameter lengths do not match");
// Add each token to the list of supported tokens.
for (uint i = 0; i < _tokens.length; i++) {
// Require that the token doesn't already exist.
address token = _tokens[i];
require(!tokens[token].exists, "token already exists");
// Store the intermediate values.
string memory symbol = _symbols[i].toSliceB32().toString();
uint magnitude = _magnitude[i];
// Add the token to the token list.
tokens[token] = Token({
symbol : symbol,
magnitude : magnitude,
rate : 0,
exists : true,
lastUpdate: _updateDate
});
// Add the token address to the address list.
_tokenAddresses.push(token);
// Emit token addition event.
emit AddedToken(msg.sender, token, symbol, magnitude);
}
}
/// @dev Remove ERC20 tokens from the list of supported tokens.
/// @param _tokens ERC20 token contract addresses.
function removeTokens(address[] _tokens) external onlyController {
// Delete each token object from the list of supported tokens based on the addresses provided.
for (uint i = 0; i < _tokens.length; i++) {
//token must exist, reverts on duplicates as well
require(tokens[_tokens[i]].exists, "token does not exist");
// Store the token address.
address token = _tokens[i];
// Delete the token object.
delete tokens[token];
// Remove the token address from the address list.
for (uint j = 0; j < _tokenAddresses.length.sub(1); j++) {
if (_tokenAddresses[j] == token) {
_tokenAddresses[j] = _tokenAddresses[_tokenAddresses.length.sub(1)];
break;
}
}
_tokenAddresses.length--;
// Emit token removal event.
emit RemovedToken(msg.sender, token);
}
}
/// @dev Update ERC20 token exchange rate manually.
/// @param _token ERC20 token contract address.
/// @param _rate ERC20 token exchange rate in wei.
/// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.
function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyController {
// Require that the token exists.
require(tokens[_token].exists, "token does not exist");
// Update the token's rate.
tokens[_token].rate = _rate;
// Update the token's last update timestamp.
tokens[_token].lastUpdate = _updateDate;
// Emit the rate update event.
emit UpdatedTokenRate(msg.sender, _token, _rate);
}
/// @dev Update ERC20 token exchange rates for all supported tokens.
//// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback
function updateTokenRates(uint _gasLimit) external payable onlyController {
_updateTokenRates(_gasLimit);
}
//// @dev Withdraw ether from the smart contract to the specified account.
function withdraw(address _to, uint _amount) external onlyController {
_to.transfer(_amount);
}
//// @dev Handle Oraclize query callback and verifiy the provided origin proof.
//// @param _queryID Oraclize query ID.
//// @param _result query result in JSON format.
//// @param _proof origin proof from crypto compare.
// solium-disable-next-line mixedcase
function __callback(bytes32 _queryID, string _result, bytes _proof) public {
// Require that the caller is the Oraclize contract.
require(msg.sender == oraclize_cbAddress(), "sender is not oraclize");
// Use the query ID to find the matching token address.
address _token = _queryToToken[_queryID];
require(_token != address(0), "queryID matches to address 0");
// Get the corresponding token object.
Token storage token = tokens[_token];
bool valid;
uint timestamp;
(valid, timestamp) = _verifyProof(_result, _proof, APIPublicKey, token.lastUpdate);
// Require that the proof is valid.
if (valid) {
// Parse the JSON result to get the rate in wei.
token.rate = _parseIntScientificWei(parseRate(_result));
// Set the update time of the token rate.
token.lastUpdate = timestamp;
// Remove query from the list.
delete _queryToToken[_queryID];
// Emit the rate update event.
emit UpdatedTokenRate(msg.sender, _token, token.rate);
}
}
/// @dev Re-usable helper function that performs the Oraclize Query.
//// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback
function _updateTokenRates(uint _gasLimit) private {
// Check if there are any existing tokens.
if (_tokenAddresses.length == 0) {
// Emit a query failure event.
emit FailedUpdateRequest("no tokens");
// Check if the contract has enough Ether to pay for the query.
} else if (oraclize_getPrice("URL") * _tokenAddresses.length > address(this).balance) {
// Emit a query failure event.
emit FailedUpdateRequest("insufficient balance");
} else {
// Set up the cryptocompare API query strings.
strings.slice memory apiPrefix = "https://min-api.cryptocompare.com/data/price?fsym=".toSlice();
strings.slice memory apiSuffix = "&tsyms=ETH&sign=true".toSlice();
// Create a new oraclize query for each supported token.
for (uint i = 0; i < _tokenAddresses.length; i++) {
// Store the token symbol used in the query.
strings.slice memory symbol = tokens[_tokenAddresses[i]].symbol.toSlice();
// Create a new oraclize query from the component strings.
bytes32 queryID = oraclize_query("URL", apiPrefix.concat(symbol).toSlice().concat(apiSuffix), _gasLimit);
// Store the query ID together with the associated token address.
_queryToToken[queryID] = _tokenAddresses[i];
// Emit the query success event.
emit RequestedUpdate(symbol.toString());
}
}
}
/// @dev Verify the origin proof returned by the cryptocompare API.
/// @param _result query result in JSON format.
/// @param _proof origin proof from cryptocompare.
/// @param _publicKey cryptocompare public key.
/// @param _lastUpdate timestamp of the last time the requested token was updated.
function _verifyProof(string _result, bytes _proof, bytes _publicKey, uint _lastUpdate) private returns (bool, uint) {
//expecting fixed length proofs
if (_proof.length != PROOF_LEN)
revert("invalid proof length");
//proof should be 65 bytes long: R (32 bytes) + S (32 bytes) + v (1 byte)
if (uint(_proof[1]) != ECDSA_SIG_LEN)
revert("invalid signature length");
bytes memory signature = new bytes(ECDSA_SIG_LEN);
signature = copyBytes(_proof, 2, ECDSA_SIG_LEN, signature, 0);
// Extract the headers, big endian encoding of headers length
if (uint(_proof[ENCODING_BYTES + ECDSA_SIG_LEN]) * MAX_BYTE_SIZE + uint(_proof[ENCODING_BYTES + ECDSA_SIG_LEN + 1]) != HEADERS_LEN)
revert("invalid headers length");
bytes memory headers = new bytes(HEADERS_LEN);
headers = copyBytes(_proof, 2*ENCODING_BYTES + ECDSA_SIG_LEN, HEADERS_LEN, headers, 0);
// Check if the signature is valid and if the signer address is matching.
if (!_verifySignature(headers, signature, _publicKey)) {
revert("invalid signature");
}
// Check if the date is valid.
bytes memory dateHeader = new bytes(20);
//keep only the relevant string(e.g. "16 Nov 2018 16:22:18")
dateHeader = copyBytes(headers, 11, 20, dateHeader, 0);
bool dateValid;
uint timestamp;
(dateValid, timestamp) = _verifyDate(string(dateHeader), _lastUpdate);
// Check whether the date returned is valid or not
if (!dateValid)
revert("invalid date");
// Check if the signed digest hash matches the result hash.
bytes memory digest = new bytes(DIGEST_BASE64_LEN);
digest = copyBytes(headers, DIGEST_OFFSET, DIGEST_BASE64_LEN, digest, 0);
if (keccak256(abi.encodePacked(sha256(abi.encodePacked(_result)))) != keccak256(_base64decode(digest)))
revert("result hash not matching");
emit VerifiedProof(_publicKey, _result);
return (true, timestamp);
}
/// @dev Verify the HTTP headers and the signature
/// @param _headers HTTP headers provided by the cryptocompare api
/// @param _signature signature provided by the cryptocompare api
/// @param _publicKey cryptocompare public key.
function _verifySignature(bytes _headers, bytes _signature, bytes _publicKey) private returns (bool) {
address signer;
bool signatureOK;
// Checks if the signature is valid by hashing the headers
(signatureOK, signer) = ecrecovery(sha256(_headers), _signature);
return signatureOK && signer == address(keccak256(_publicKey));
}
/// @dev Verify the signed HTTP date header.
/// @param _dateHeader extracted date string e.g. Wed, 12 Sep 2018 15:18:14 GMT.
/// @param _lastUpdate timestamp of the last time the requested token was updated.
function _verifyDate(string _dateHeader, uint _lastUpdate) private pure returns (bool, uint) {
//called by verifyProof(), _dateHeader is always a string of length = 20
assert(abi.encodePacked(_dateHeader).length == 20);
//Split the date string and get individual date components.
strings.slice memory date = _dateHeader.toSlice();
strings.slice memory timeDelimiter = ":".toSlice();
strings.slice memory dateDelimiter = " ".toSlice();
uint day = _parseIntScientific(date.split(dateDelimiter).toString());
require(day > 0 && day < 32, "day error");
uint month = _monthToNumber(date.split(dateDelimiter).toString());
require(month > 0 && month < 13, "month error");
uint year = _parseIntScientific(date.split(dateDelimiter).toString());
require(year > 2017 && year < 3000, "year error");
uint hour = _parseIntScientific(date.split(timeDelimiter).toString());
require(hour < 25, "hour error");
uint minute = _parseIntScientific(date.split(timeDelimiter).toString());
require(minute < 60, "minute error");
uint second = _parseIntScientific(date.split(timeDelimiter).toString());
require(second < 60, "second error");
uint timestamp = year * (10 ** 10) + month * (10 ** 8) + day * (10 ** 6) + hour * (10 ** 4) + minute * (10 ** 2) + second;
return (timestamp > _lastUpdate, timestamp);
}
} | indicated if the exponent is negative
| bool minus = false; | 990,948 | [
1,
728,
11780,
309,
326,
9100,
353,
6092,
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,
3639,
1426,
12647,
273,
629,
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
] |
// SPDX-License-Identifier: MIT
// solhint-disable
/*
This is copied from OZ preset: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/release-v3.0.0/contracts/presets/ERC721PresetMinterPauserAutoId.sol
Alterations:
* Make the counter public, so that we can use it in our custom mint function
* Removed ERC721Burnable parent contract, but added our own custom burn function.
* Removed original "mint" function, because we have a custom one.
* Removed default initialization functions, because they set msg.sender as the owner, which
we do not want, because we use a deployer account, which is separate from the protocol owner.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Counters.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Pausable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
/**
* @dev {ERC721} 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
* - token ID and URI autogeneration
*
* 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 aother accounts
*/
contract ERC721PresetMinterPauserAutoIdUpgradeSafe is
Initializable,
ContextUpgradeSafe,
AccessControlUpgradeSafe,
ERC721PausableUpgradeSafe
{
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
Counters.Counter public _tokenIdTracker;
/**
* @dev Pauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721PausableUpgradeSafe) {
super._beforeTokenTransfer(from, to, tokenId);
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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, _msgSender()));
* ...
* }
* ```
*
* 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}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_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) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_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 {
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.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../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.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
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;
}
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. 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;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
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 {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
import "../../Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721UpgradeSafe is Initializable, ContextUpgradeSafe, ERC165UpgradeSafe, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// 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;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
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;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If a base URI is set (via {_setBaseURI}), it is added as a prefix to the
* token's own URI (via {_setTokenURI}).
*
* If there is a base URI but no token URI, the token's ID will be used as
* its URI when appending it to the base URI. This pattern for autogenerated
* token URIs can lead to large gas savings.
*
* .Examples
* |===
* |`_setBaseURI()` |`_setTokenURI()` |`tokenURI()`
* | ""
* | ""
* | ""
* | ""
* | "token.uri/123"
* | "token.uri/123"
* | "token.uri/"
* | "123"
* | "token.uri/123"
* | "token.uri/"
* | ""
* | "token.uri/<tokenId>"
* |===
*
* Requirements:
*
* - `tokenId` must exist.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = 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 Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param operator operator address to set the approval
* @param approved representing the status of the approval to be set
*/
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 Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
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 Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
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 the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
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 the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
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 Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: If all token IDs share a prefix (for example, if your URIs look like
* `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @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()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @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[41] private __gap;
}
pragma solidity ^0.6.0;
import "./ERC721.sol";
import "../../utils/Pausable.sol";
import "../../Initializable.sol";
/**
* @dev ERC721 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.
*/
abstract contract ERC721PausableUpgradeSafe is Initializable, ERC721UpgradeSafe, PausableUpgradeSafe {
function __ERC721Pausable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
}
function __ERC721Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
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 use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been 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;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
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));
}
}
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");
}
}
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) {
// 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;
}
}
pragma solidity ^0.6.2;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
pragma solidity ^0.6.2;
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 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity ^0.6.2;
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 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
pragma solidity ^0.6.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
pragma solidity ^0.6.0;
import "./IERC165.sol";
import "../Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165UpgradeSafe is Initializable, IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` 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);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
pragma solidity ^0.6.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);
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../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.
*/
contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe {
/**
* @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 returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "../external/ERC721PresetMinterPauserAutoId.sol";
import "../interfaces/IERC20withDec.sol";
import "../interfaces/ISeniorPool.sol";
import "../protocol/core/GoldfinchConfig.sol";
import "../protocol/core/ConfigHelper.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../library/StakingRewardsVesting.sol";
contract StakingRewards is ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20withDec;
using ConfigHelper for GoldfinchConfig;
using StakingRewardsVesting for StakingRewardsVesting.Rewards;
enum LockupPeriod {
SixMonths,
TwelveMonths,
TwentyFourMonths
}
struct StakedPosition {
// @notice Staked amount denominated in `stakingToken().decimals()`
uint256 amount;
// @notice Struct describing rewards owed with vesting
StakingRewardsVesting.Rewards rewards;
// @notice Multiplier applied to staked amount when locking up position
uint256 leverageMultiplier;
// @notice Time in seconds after which position can be unstaked
uint256 lockedUntil;
}
/* ========== EVENTS =================== */
event RewardsParametersUpdated(
address indexed who,
uint256 targetCapacity,
uint256 minRate,
uint256 maxRate,
uint256 minRateAtPercent,
uint256 maxRateAtPercent
);
event TargetCapacityUpdated(address indexed who, uint256 targetCapacity);
event VestingScheduleUpdated(address indexed who, uint256 vestingLength);
event MinRateUpdated(address indexed who, uint256 minRate);
event MaxRateUpdated(address indexed who, uint256 maxRate);
event MinRateAtPercentUpdated(address indexed who, uint256 minRateAtPercent);
event MaxRateAtPercentUpdated(address indexed who, uint256 maxRateAtPercent);
event LeverageMultiplierUpdated(address indexed who, LockupPeriod lockupPeriod, uint256 leverageMultiplier);
/* ========== STATE VARIABLES ========== */
uint256 private constant MULTIPLIER_DECIMALS = 1e18;
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
GoldfinchConfig public config;
/// @notice The block timestamp when rewards were last checkpointed
uint256 public lastUpdateTime;
/// @notice Accumulated rewards per token at the last checkpoint
uint256 public accumulatedRewardsPerToken;
/// @notice Total rewards available for disbursement at the last checkpoint, denominated in `rewardsToken()`
uint256 public rewardsAvailable;
/// @notice StakedPosition tokenId => accumulatedRewardsPerToken at the position's last checkpoint
mapping(uint256 => uint256) public positionToAccumulatedRewardsPerToken;
/// @notice Desired supply of staked tokens. The reward rate adjusts in a range
/// around this value to incentivize staking or unstaking to maintain it.
uint256 public targetCapacity;
/// @notice The minimum total disbursed rewards per second, denominated in `rewardsToken()`
uint256 public minRate;
/// @notice The maximum total disbursed rewards per second, denominated in `rewardsToken()`
uint256 public maxRate;
/// @notice The percent of `targetCapacity` at which the reward rate reaches `maxRate`.
/// Represented with `MULTIPLIER_DECIMALS`.
uint256 public maxRateAtPercent;
/// @notice The percent of `targetCapacity` at which the reward rate reaches `minRate`.
/// Represented with `MULTIPLIER_DECIMALS`.
uint256 public minRateAtPercent;
/// @notice The duration in seconds over which rewards vest
uint256 public vestingLength;
/// @dev Supply of staked tokens, excluding leverage due to lock-up boosting, denominated in
/// `stakingToken().decimals()`
uint256 public totalStakedSupply;
/// @dev Supply of staked tokens, including leverage due to lock-up boosting, denominated in
/// `stakingToken().decimals()`
uint256 private totalLeveragedStakedSupply;
/// @dev A mapping from lockup periods to leverage multipliers used to boost rewards.
/// See `stakeWithLockup`.
mapping(LockupPeriod => uint256) private leverageMultipliers;
/// @dev NFT tokenId => staked position
mapping(uint256 => StakedPosition) public positions;
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) external initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained("Goldfinch V2 LP Staking Tokens", "GFI-V2-LPS");
__ERC721Pausable_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
config = _config;
vestingLength = 365 days;
// Set defaults for leverage multipliers (no boosting)
leverageMultipliers[LockupPeriod.SixMonths] = MULTIPLIER_DECIMALS; // 1x
leverageMultipliers[LockupPeriod.TwelveMonths] = MULTIPLIER_DECIMALS; // 1x
leverageMultipliers[LockupPeriod.TwentyFourMonths] = MULTIPLIER_DECIMALS; // 1x
}
/* ========== VIEWS ========== */
/// @notice Returns the staked balance of a given position token
/// @param tokenId A staking position token ID
/// @return Amount of staked tokens denominated in `stakingToken().decimals()`
function stakedBalanceOf(uint256 tokenId) external view returns (uint256) {
return positions[tokenId].amount;
}
/// @notice The address of the token being disbursed as rewards
function rewardsToken() public view returns (IERC20withDec) {
return config.getGFI();
}
/// @notice The address of the token that can be staked
function stakingToken() public view returns (IERC20withDec) {
return config.getFidu();
}
/// @notice The additional rewards earned per token, between the provided time and the last
/// time rewards were checkpointed, given the prevailing `rewardRate()`. This amount is limited
/// by the amount of rewards that are available for distribution; if there aren't enough
/// rewards in the balance of this contract, then we shouldn't be giving them out.
/// @return Amount of rewards denominated in `rewardsToken().decimals()`.
function additionalRewardsPerTokenSinceLastUpdate(uint256 time) internal view returns (uint256) {
require(time >= lastUpdateTime, "Invalid end time for range");
if (totalLeveragedStakedSupply == 0) {
return 0;
}
uint256 rewardsSinceLastUpdate = Math.min(time.sub(lastUpdateTime).mul(rewardRate()), rewardsAvailable);
uint256 additionalRewardsPerToken = rewardsSinceLastUpdate.mul(stakingTokenMantissa()).div(
totalLeveragedStakedSupply
);
// Prevent perverse, infinite-mint scenario where totalLeveragedStakedSupply is a fraction of a token.
// Since it's used as the denominator, this could make additionalRewardPerToken larger than the total number
// of tokens that should have been disbursed in the elapsed time. The attacker would need to find
// a way to reduce totalLeveragedStakedSupply while maintaining a staked position of >= 1.
// See: https://twitter.com/Mudit__Gupta/status/1409463917290557440
if (additionalRewardsPerToken > rewardsSinceLastUpdate) {
return 0;
}
return additionalRewardsPerToken;
}
/// @notice Returns accumulated rewards per token up to the current block timestamp
/// @return Amount of rewards denominated in `rewardsToken().decimals()`
function rewardPerToken() public view returns (uint256) {
uint256 additionalRewardsPerToken = additionalRewardsPerTokenSinceLastUpdate(block.timestamp);
return accumulatedRewardsPerToken.add(additionalRewardsPerToken);
}
/// @notice Returns rewards earned by a given position token from its last checkpoint up to the
/// current block timestamp.
/// @param tokenId A staking position token ID
/// @return Amount of rewards denominated in `rewardsToken().decimals()`
function earnedSinceLastCheckpoint(uint256 tokenId) public view returns (uint256) {
StakedPosition storage position = positions[tokenId];
uint256 leveredAmount = positionToLeveredAmount(position);
return
leveredAmount.mul(rewardPerToken().sub(positionToAccumulatedRewardsPerToken[tokenId])).div(
stakingTokenMantissa()
);
}
/// @notice Returns the rewards claimable by a given position token at the most recent checkpoint, taking into
/// account vesting schedule.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function claimableRewards(uint256 tokenId) public view returns (uint256 rewards) {
return positions[tokenId].rewards.claimable();
}
/// @notice Returns the rewards that will have vested for some position with the given params.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function totalVestedAt(
uint256 start,
uint256 end,
uint256 time,
uint256 grantedAmount
) external pure returns (uint256 rewards) {
return StakingRewardsVesting.totalVestedAt(start, end, time, grantedAmount);
}
/// @notice Number of rewards, in `rewardsToken().decimals()`, to disburse each second
function rewardRate() internal view returns (uint256) {
// The reward rate can be thought of as a piece-wise function:
//
// let intervalStart = (maxRateAtPercent * targetCapacity),
// intervalEnd = (minRateAtPercent * targetCapacity),
// x = totalStakedSupply
// in
// if x < intervalStart
// y = maxRate
// if x > intervalEnd
// y = minRate
// else
// y = maxRate - (maxRate - minRate) * (x - intervalStart) / (intervalEnd - intervalStart)
//
// See an example here:
// solhint-disable-next-line max-line-length
// https://www.wolframalpha.com/input/?i=Piecewise%5B%7B%7B1000%2C+x+%3C+50%7D%2C+%7B100%2C+x+%3E+300%7D%2C+%7B1000+-+%281000+-+100%29+*+%28x+-+50%29+%2F+%28300+-+50%29+%2C+50+%3C+x+%3C+300%7D%7D%5D
//
// In that example:
// maxRateAtPercent = 0.5, minRateAtPercent = 3, targetCapacity = 100, maxRate = 1000, minRate = 100
uint256 intervalStart = targetCapacity.mul(maxRateAtPercent).div(MULTIPLIER_DECIMALS);
uint256 intervalEnd = targetCapacity.mul(minRateAtPercent).div(MULTIPLIER_DECIMALS);
uint256 x = totalStakedSupply;
// Subsequent computation would overflow
if (intervalEnd <= intervalStart) {
return 0;
}
if (x < intervalStart) {
return maxRate;
}
if (x > intervalEnd) {
return minRate;
}
return maxRate.sub(maxRate.sub(minRate).mul(x.sub(intervalStart)).div(intervalEnd.sub(intervalStart)));
}
function positionToLeveredAmount(StakedPosition storage position) internal view returns (uint256) {
return toLeveredAmount(position.amount, position.leverageMultiplier);
}
function toLeveredAmount(uint256 amount, uint256 leverageMultiplier) internal pure returns (uint256) {
return amount.mul(leverageMultiplier).div(MULTIPLIER_DECIMALS);
}
function stakingTokenMantissa() internal view returns (uint256) {
return uint256(10)**stakingToken().decimals();
}
/// @notice The amount of rewards currently being earned per token per second. This amount takes into
/// account how many rewards are actually available for disbursal -- unlike `rewardRate()` which does not.
/// This function is intended for public consumption, to know the rate at which rewards are being
/// earned, and not as an input to the mutative calculations in this contract.
/// @return Amount of rewards denominated in `rewardsToken().decimals()`.
function currentEarnRatePerToken() public view returns (uint256) {
uint256 time = block.timestamp == lastUpdateTime ? block.timestamp + 1 : block.timestamp;
uint256 elapsed = time.sub(lastUpdateTime);
return additionalRewardsPerTokenSinceLastUpdate(time).div(elapsed);
}
/// @notice The amount of rewards currently being earned per second, for a given position. This function
/// is intended for public consumption, to know the rate at which rewards are being earned
/// for a given position, and not as an input to the mutative calculations in this contract.
/// @return Amount of rewards denominated in `rewardsToken().decimals()`.
function positionCurrentEarnRate(uint256 tokenId) external view returns (uint256) {
StakedPosition storage position = positions[tokenId];
uint256 leveredAmount = positionToLeveredAmount(position);
return currentEarnRatePerToken().mul(leveredAmount).div(stakingTokenMantissa());
}
/* ========== MUTATIVE FUNCTIONS ========== */
/// @notice Stake `stakingToken()` to earn rewards. When you call this function, you'll receive an
/// an NFT representing your staked position. You can present your NFT to `getReward` or `unstake`
/// to claim rewards or unstake your tokens respectively. Rewards vest over a schedule.
/// @dev This function checkpoints rewards.
/// @param amount The amount of `stakingToken()` to stake
function stake(uint256 amount) external nonReentrant whenNotPaused updateReward(0) {
_stakeWithLockup(msg.sender, msg.sender, amount, 0, MULTIPLIER_DECIMALS);
}
/// @notice Stake `stakingToken()` and lock your position for a period of time to boost your rewards.
/// When you call this function, you'll receive an an NFT representing your staked position.
/// You can present your NFT to `getReward` or `unstake` to claim rewards or unstake your tokens
/// respectively. Rewards vest over a schedule.
///
/// A locked position's rewards are boosted using a multiplier on the staked balance. For example,
/// if I lock 100 tokens for a 2x multiplier, my rewards will be calculated as if I staked 200 tokens.
/// This mechanism is similar to curve.fi's CRV-boosting vote-locking. Locked positions cannot be
/// unstaked until after the position's lockedUntil timestamp.
/// @dev This function checkpoints rewards.
/// @param amount The amount of `stakingToken()` to stake
/// @param lockupPeriod The period over which to lock staked tokens
function stakeWithLockup(uint256 amount, LockupPeriod lockupPeriod)
external
nonReentrant
whenNotPaused
updateReward(0)
{
uint256 lockDuration = lockupPeriodToDuration(lockupPeriod);
uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod);
uint256 lockedUntil = block.timestamp.add(lockDuration);
_stakeWithLockup(msg.sender, msg.sender, amount, lockedUntil, leverageMultiplier);
}
/// @notice Deposit to SeniorPool and stake your shares in the same transaction.
/// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit
/// will be staked.
function depositAndStake(uint256 usdcAmount) public nonReentrant whenNotPaused updateReward(0) {
uint256 fiduAmount = depositToSeniorPool(usdcAmount);
uint256 lockedUntil = 0;
uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS);
emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS);
}
function depositToSeniorPool(uint256 usdcAmount) internal returns (uint256 fiduAmount) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
IERC20withDec usdc = config.getUSDC();
usdc.safeTransferFrom(msg.sender, address(this), usdcAmount);
ISeniorPool seniorPool = config.getSeniorPool();
usdc.safeIncreaseAllowance(address(seniorPool), usdcAmount);
return seniorPool.deposit(usdcAmount);
}
/// @notice Identical to `depositAndStake`, except it allows for a signature to be passed that permits
/// this contract to move funds on behalf of the user.
/// @param usdcAmount The amount of USDC to deposit
/// @param v secp256k1 signature component
/// @param r secp256k1 signature component
/// @param s secp256k1 signature component
function depositWithPermitAndStake(
uint256 usdcAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s);
depositAndStake(usdcAmount);
}
/// @notice Deposit to the `SeniorPool` and stake your shares with a lock-up in the same transaction.
/// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit
/// will be staked.
/// @param lockupPeriod The period over which to lock staked tokens
function depositAndStakeWithLockup(uint256 usdcAmount, LockupPeriod lockupPeriod)
public
nonReentrant
whenNotPaused
updateReward(0)
{
uint256 fiduAmount = depositToSeniorPool(usdcAmount);
uint256 lockDuration = lockupPeriodToDuration(lockupPeriod);
uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod);
uint256 lockedUntil = block.timestamp.add(lockDuration);
uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, leverageMultiplier);
emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, leverageMultiplier);
}
function lockupPeriodToDuration(LockupPeriod lockupPeriod) internal pure returns (uint256 lockDuration) {
if (lockupPeriod == LockupPeriod.SixMonths) {
return 365 days / 2;
} else if (lockupPeriod == LockupPeriod.TwelveMonths) {
return 365 days;
} else if (lockupPeriod == LockupPeriod.TwentyFourMonths) {
return 365 days * 2;
} else {
revert("unsupported LockupPeriod");
}
}
/// @notice Get the leverage multiplier used to boost rewards for a given lockup period.
/// See `stakeWithLockup`. The leverage multiplier is denominated in `MULTIPLIER_DECIMALS`.
function getLeverageMultiplier(LockupPeriod lockupPeriod) public view returns (uint256) {
uint256 leverageMultiplier = leverageMultipliers[lockupPeriod];
require(leverageMultiplier > 0, "unsupported LockupPeriod");
return leverageMultiplier;
}
/// @notice Identical to `depositAndStakeWithLockup`, except it allows for a signature to be passed that permits
/// this contract to move funds on behalf of the user.
/// @param usdcAmount The amount of USDC to deposit
/// @param lockupPeriod The period over which to lock staked tokens
/// @param v secp256k1 signature component
/// @param r secp256k1 signature component
/// @param s secp256k1 signature component
function depositWithPermitAndStakeWithLockup(
uint256 usdcAmount,
LockupPeriod lockupPeriod,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s);
depositAndStakeWithLockup(usdcAmount, lockupPeriod);
}
function _stakeWithLockup(
address staker,
address nftRecipient,
uint256 amount,
uint256 lockedUntil,
uint256 leverageMultiplier
) internal returns (uint256 tokenId) {
require(amount > 0, "Cannot stake 0");
_tokenIdTracker.increment();
tokenId = _tokenIdTracker.current();
// Ensure we snapshot accumulatedRewardsPerToken for tokenId after it is available
// We do this before setting the position, because we don't want `earned` to (incorrectly) account for
// position.amount yet. This is equivalent to using the updateReward(msg.sender) modifier in the original
// synthetix contract, where the modifier is called before any staking balance for that address is recorded
_updateReward(tokenId);
positions[tokenId] = StakedPosition({
amount: amount,
rewards: StakingRewardsVesting.Rewards({
totalUnvested: 0,
totalVested: 0,
totalPreviouslyVested: 0,
totalClaimed: 0,
startTime: block.timestamp,
endTime: block.timestamp.add(vestingLength)
}),
leverageMultiplier: leverageMultiplier,
lockedUntil: lockedUntil
});
_mint(nftRecipient, tokenId);
uint256 leveredAmount = positionToLeveredAmount(positions[tokenId]);
totalLeveragedStakedSupply = totalLeveragedStakedSupply.add(leveredAmount);
totalStakedSupply = totalStakedSupply.add(amount);
// Staker is address(this) when using depositAndStake or other convenience functions
if (staker != address(this)) {
stakingToken().safeTransferFrom(staker, address(this), amount);
}
emit Staked(nftRecipient, tokenId, amount, lockedUntil, leverageMultiplier);
return tokenId;
}
/// @notice Unstake an amount of `stakingToken()` associated with a given position and transfer to msg.sender.
/// Unvested rewards will be forfeited, but remaining staked amount will continue to accrue rewards.
/// Positions that are still locked cannot be unstaked until the position's lockedUntil time has passed.
/// @dev This function checkpoints rewards
/// @param tokenId A staking position token ID
/// @param amount Amount of `stakingToken()` to be unstaked from the position
function unstake(uint256 tokenId, uint256 amount) public nonReentrant whenNotPaused updateReward(tokenId) {
_unstake(tokenId, amount);
stakingToken().safeTransfer(msg.sender, amount);
}
function unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) public nonReentrant whenNotPaused {
(uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenId, usdcAmount);
emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount);
}
function _unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount)
internal
updateReward(tokenId)
returns (uint256 usdcAmountReceived, uint256 fiduUsed)
{
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
ISeniorPool seniorPool = config.getSeniorPool();
IFidu fidu = config.getFidu();
uint256 fiduBalanceBefore = fidu.balanceOf(address(this));
usdcAmountReceived = seniorPool.withdraw(usdcAmount);
fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this)));
_unstake(tokenId, fiduUsed);
config.getUSDC().safeTransfer(msg.sender, usdcAmountReceived);
return (usdcAmountReceived, fiduUsed);
}
function unstakeAndWithdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata usdcAmounts)
public
nonReentrant
whenNotPaused
{
require(tokenIds.length == usdcAmounts.length, "tokenIds and usdcAmounts must be the same length");
uint256 usdcReceivedAmountTotal = 0;
uint256[] memory fiduAmounts = new uint256[](usdcAmounts.length);
for (uint256 i = 0; i < usdcAmounts.length; i++) {
(uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenIds[i], usdcAmounts[i]);
usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount);
fiduAmounts[i] = fiduAmount;
}
emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts);
}
function unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) public nonReentrant whenNotPaused {
uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenId, fiduAmount);
emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount);
}
function _unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount)
internal
updateReward(tokenId)
returns (uint256 usdcReceivedAmount)
{
usdcReceivedAmount = config.getSeniorPool().withdrawInFidu(fiduAmount);
_unstake(tokenId, fiduAmount);
config.getUSDC().safeTransfer(msg.sender, usdcReceivedAmount);
return usdcReceivedAmount;
}
function unstakeAndWithdrawMultipleInFidu(uint256[] calldata tokenIds, uint256[] calldata fiduAmounts)
public
nonReentrant
whenNotPaused
{
require(tokenIds.length == fiduAmounts.length, "tokenIds and usdcAmounts must be the same length");
uint256 usdcReceivedAmountTotal = 0;
for (uint256 i = 0; i < fiduAmounts.length; i++) {
uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenIds[i], fiduAmounts[i]);
usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount);
}
emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts);
}
function _unstake(uint256 tokenId, uint256 amount) internal {
require(ownerOf(tokenId) == msg.sender, "access denied");
require(amount > 0, "Cannot unstake 0");
StakedPosition storage position = positions[tokenId];
uint256 prevAmount = position.amount;
require(amount <= prevAmount, "cannot unstake more than staked balance");
require(block.timestamp >= position.lockedUntil, "staked funds are locked");
// By this point, leverageMultiplier should always be 1x due to the reset logic in updateReward.
// But we subtract leveredAmount from totalLeveragedStakedSupply anyway, since that is technically correct.
uint256 leveredAmount = toLeveredAmount(amount, position.leverageMultiplier);
totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(leveredAmount);
totalStakedSupply = totalStakedSupply.sub(amount);
position.amount = prevAmount.sub(amount);
// Slash unvested rewards
uint256 slashingPercentage = amount.mul(StakingRewardsVesting.PERCENTAGE_DECIMALS).div(prevAmount);
position.rewards.slash(slashingPercentage);
emit Unstaked(msg.sender, tokenId, amount);
}
/// @notice "Kick" a user's reward multiplier. If they are past their lock-up period, their reward
/// multipler will be reset to 1x.
/// @dev This will also checkpoint their rewards up to the current time.
// solhint-disable-next-line no-empty-blocks
function kick(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) {}
/// @notice Claim rewards for a given staked position
/// @param tokenId A staking position token ID
function getReward(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) {
require(ownerOf(tokenId) == msg.sender, "access denied");
uint256 reward = claimableRewards(tokenId);
if (reward > 0) {
positions[tokenId].rewards.claim(reward);
rewardsToken().safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, tokenId, reward);
}
}
/// @notice Unstake the position's full amount and claim all rewards
/// @param tokenId A staking position token ID
function exit(uint256 tokenId) external {
unstake(tokenId, positions[tokenId].amount);
getReward(tokenId);
}
function exitAndWithdraw(uint256 tokenId) external {
unstakeAndWithdrawInFidu(tokenId, positions[tokenId].amount);
getReward(tokenId);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/// @notice Transfer rewards from msg.sender, to be used for reward distribution
function loadRewards(uint256 rewards) public onlyAdmin updateReward(0) {
rewardsToken().safeTransferFrom(msg.sender, address(this), rewards);
rewardsAvailable = rewardsAvailable.add(rewards);
emit RewardAdded(rewards);
}
function setRewardsParameters(
uint256 _targetCapacity,
uint256 _minRate,
uint256 _maxRate,
uint256 _minRateAtPercent,
uint256 _maxRateAtPercent
) public onlyAdmin updateReward(0) {
require(_maxRate >= _minRate, "maxRate must be >= then minRate");
require(_maxRateAtPercent <= _minRateAtPercent, "maxRateAtPercent must be <= minRateAtPercent");
targetCapacity = _targetCapacity;
minRate = _minRate;
maxRate = _maxRate;
minRateAtPercent = _minRateAtPercent;
maxRateAtPercent = _maxRateAtPercent;
emit RewardsParametersUpdated(msg.sender, targetCapacity, minRate, maxRate, minRateAtPercent, maxRateAtPercent);
}
function setLeverageMultiplier(LockupPeriod lockupPeriod, uint256 leverageMultiplier)
public
onlyAdmin
updateReward(0)
{
leverageMultipliers[lockupPeriod] = leverageMultiplier;
emit LeverageMultiplierUpdated(msg.sender, lockupPeriod, leverageMultiplier);
}
function setVestingSchedule(uint256 _vestingLength) public onlyAdmin updateReward(0) {
vestingLength = _vestingLength;
emit VestingScheduleUpdated(msg.sender, vestingLength);
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(_msgSender(), address(config));
}
/* ========== MODIFIERS ========== */
modifier updateReward(uint256 tokenId) {
_updateReward(tokenId);
_;
}
function _updateReward(uint256 tokenId) internal {
uint256 prevAccumulatedRewardsPerToken = accumulatedRewardsPerToken;
accumulatedRewardsPerToken = rewardPerToken();
uint256 rewardsJustDistributed = totalLeveragedStakedSupply
.mul(accumulatedRewardsPerToken.sub(prevAccumulatedRewardsPerToken))
.div(stakingTokenMantissa());
rewardsAvailable = rewardsAvailable.sub(rewardsJustDistributed);
lastUpdateTime = block.timestamp;
if (tokenId != 0) {
uint256 additionalRewards = earnedSinceLastCheckpoint(tokenId);
StakedPosition storage position = positions[tokenId];
StakingRewardsVesting.Rewards storage rewards = position.rewards;
rewards.totalUnvested = rewards.totalUnvested.add(additionalRewards);
rewards.checkpoint();
positionToAccumulatedRewardsPerToken[tokenId] = accumulatedRewardsPerToken;
// If position is unlocked, reset its leverageMultiplier back to 1x
uint256 lockedUntil = position.lockedUntil;
uint256 leverageMultiplier = position.leverageMultiplier;
uint256 amount = position.amount;
if (lockedUntil > 0 && block.timestamp >= lockedUntil && leverageMultiplier > MULTIPLIER_DECIMALS) {
uint256 prevLeveredAmount = toLeveredAmount(amount, leverageMultiplier);
uint256 newLeveredAmount = toLeveredAmount(amount, MULTIPLIER_DECIMALS);
position.leverageMultiplier = MULTIPLIER_DECIMALS;
totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(prevLeveredAmount).add(newLeveredAmount);
}
}
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 indexed tokenId, uint256 amount, uint256 lockedUntil, uint256 multiplier);
event DepositedAndStaked(
address indexed user,
uint256 depositedAmount,
uint256 indexed tokenId,
uint256 amount,
uint256 lockedUntil,
uint256 multiplier
);
event Unstaked(address indexed user, uint256 indexed tokenId, uint256 amount);
event UnstakedAndWithdrew(address indexed user, uint256 usdcReceivedAmount, uint256 indexed tokenId, uint256 amount);
event UnstakedAndWithdrewMultiple(
address indexed user,
uint256 usdcReceivedAmount,
uint256[] tokenIds,
uint256[] amounts
);
event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
}
pragma solidity ^0.6.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);
}
}
pragma solidity ^0.6.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 ERC20;` 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));
}
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.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "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");
}
}
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/**
* @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].
*/
contract ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// Storing an initial 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 percetange 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.
_notEntered = true;
}
/**
* @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(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
/*
Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's.
*/
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20withDec is IERC20 {
/**
* @dev Returns the number of decimals used for the token
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ITranchedPool.sol";
abstract contract ISeniorPool {
uint256 public sharePrice;
uint256 public totalLoansOutstanding;
uint256 public totalWritedowns;
function deposit(uint256 amount) external virtual returns (uint256 depositShares);
function depositWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual returns (uint256 depositShares);
function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount);
function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount);
function sweepToCompound() public virtual;
function sweepFromCompound() public virtual;
function invest(ITranchedPool pool) public virtual;
function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256);
function redeem(uint256 tokenId) public virtual;
function writedown(uint256 tokenId) public virtual;
function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount);
function assets() public view virtual returns (uint256);
function getNumShares(uint256 amount) public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "../../interfaces/IGoldfinchConfig.sol";
import "./ConfigOptions.sol";
/**
* @title GoldfinchConfig
* @notice This contract stores mappings of useful "protocol config state", giving a central place
* for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars
* are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol.
* Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this
* is mostly to save gas costs of having each call go through a proxy)
* @author Goldfinch
*/
contract GoldfinchConfig is BaseUpgradeablePausable {
bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE");
mapping(uint256 => address) public addresses;
mapping(uint256 => uint256) public numbers;
mapping(address => bool) public goList;
event AddressUpdated(address owner, uint256 index, address oldValue, address newValue);
event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue);
event GoListed(address indexed member);
event NoListed(address indexed member);
bool public valuesInitialized;
function initialize(address owner) public initializer {
require(owner != address(0), "Owner address cannot be empty");
__BaseUpgradeablePausable__init(owner);
_setupRole(GO_LISTER_ROLE, owner);
_setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE);
}
function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin {
require(addresses[addressIndex] == address(0), "Address has already been initialized");
emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress);
addresses[addressIndex] = newAddress;
}
function setNumber(uint256 index, uint256 newNumber) public onlyAdmin {
emit NumberUpdated(msg.sender, index, numbers[index], newNumber);
numbers[index] = newNumber;
}
function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve);
emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve);
addresses[key] = newTreasuryReserve;
}
function setSeniorPoolStrategy(address newStrategy) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy);
emit AddressUpdated(msg.sender, key, addresses[key], newStrategy);
addresses[key] = newStrategy;
}
function setCreditLineImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setTranchedPoolImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.TranchedPoolImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setBorrowerImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setGoldfinchConfig(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function initializeFromOtherConfig(
address _initialConfig,
uint256 numbersLength,
uint256 addressesLength
) public onlyAdmin {
require(!valuesInitialized, "Already initialized values");
IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig);
for (uint256 i = 0; i < numbersLength; i++) {
setNumber(i, initialConfig.getNumber(i));
}
for (uint256 i = 0; i < addressesLength; i++) {
if (getAddress(i) == address(0)) {
setAddress(i, initialConfig.getAddress(i));
}
}
valuesInitialized = true;
}
/**
* @dev Adds a user to go-list
* @param _member address to add to go-list
*/
function addToGoList(address _member) public onlyGoListerRole {
goList[_member] = true;
emit GoListed(_member);
}
/**
* @dev removes a user from go-list
* @param _member address to remove from go-list
*/
function removeFromGoList(address _member) public onlyGoListerRole {
goList[_member] = false;
emit NoListed(_member);
}
/**
* @dev adds many users to go-list at once
* @param _members addresses to ad to go-list
*/
function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole {
for (uint256 i = 0; i < _members.length; i++) {
addToGoList(_members[i]);
}
}
/**
* @dev removes many users from go-list at once
* @param _members addresses to remove from go-list
*/
function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole {
for (uint256 i = 0; i < _members.length; i++) {
removeFromGoList(_members[i]);
}
}
/*
Using custom getters in case we want to change underlying implementation later,
or add checks or validations later on.
*/
function getAddress(uint256 index) public view returns (address) {
return addresses[index];
}
function getNumber(uint256 index) public view returns (uint256) {
return numbers[index];
}
modifier onlyGoListerRole() {
require(hasRole(GO_LISTER_ROLE, _msgSender()), "Must have go-lister role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "../../interfaces/IPool.sol";
import "../../interfaces/IFidu.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ICreditDesk.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ICUSDCContract.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../interfaces/IBackerRewards.sol";
import "../../interfaces/IGoldfinchFactory.sol";
import "../../interfaces/IGo.sol";
/**
* @title ConfigHelper
* @notice A convenience library for getting easy access to other contracts and constants within the
* protocol, through the use of the GoldfinchConfig contract
* @author Goldfinch
*/
library ConfigHelper {
function getPool(GoldfinchConfig config) internal view returns (IPool) {
return IPool(poolAddress(config));
}
function getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) {
return ISeniorPool(seniorPoolAddress(config));
}
function getSeniorPoolStrategy(GoldfinchConfig config) internal view returns (ISeniorPoolStrategy) {
return ISeniorPoolStrategy(seniorPoolStrategyAddress(config));
}
function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) {
return IERC20withDec(usdcAddress(config));
}
function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) {
return ICreditDesk(creditDeskAddress(config));
}
function getFidu(GoldfinchConfig config) internal view returns (IFidu) {
return IFidu(fiduAddress(config));
}
function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) {
return ICUSDCContract(cusdcContractAddress(config));
}
function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) {
return IPoolTokens(poolTokensAddress(config));
}
function getBackerRewards(GoldfinchConfig config) internal view returns (IBackerRewards) {
return IBackerRewards(backerRewardsAddress(config));
}
function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) {
return IGoldfinchFactory(goldfinchFactoryAddress(config));
}
function getGFI(GoldfinchConfig config) internal view returns (IERC20withDec) {
return IERC20withDec(gfiAddress(config));
}
function getGo(GoldfinchConfig config) internal view returns (IGo) {
return IGo(goAddress(config));
}
function oneInchAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.OneInch));
}
function creditLineImplementationAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation));
}
function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder));
}
function configAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig));
}
function poolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Pool));
}
function poolTokensAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens));
}
function backerRewardsAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.BackerRewards));
}
function seniorPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPool));
}
function seniorPoolStrategyAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPoolStrategy));
}
function creditDeskAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk));
}
function goldfinchFactoryAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory));
}
function gfiAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GFI));
}
function fiduAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Fidu));
}
function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract));
}
function usdcAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.USDC));
}
function tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation));
}
function migratedTranchedPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.MigratedTranchedPoolImplementation));
}
function reserveAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve));
}
function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin));
}
function borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation));
}
function goAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Go));
}
function stakingRewardsAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.StakingRewards));
}
function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator));
}
function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator));
}
function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays));
}
function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays));
}
function getDrawdownPeriodInSeconds(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds));
}
function getTransferRestrictionPeriodInDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays));
}
function getLeverageRatio(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LeverageRatio));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./PauserPausable.sol";
/**
* @title BaseUpgradeablePausable contract
* @notice This is our Base contract that most other contracts inherit from. It includes many standard
* useful abilities like ugpradeability, pausability, access control, and re-entrancy guards.
* @author Goldfinch
*/
contract BaseUpgradeablePausable is
Initializable,
AccessControlUpgradeSafe,
PauserPausable,
ReentrancyGuardUpgradeSafe
{
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
using SafeMath for uint256;
// Pre-reserving a few slots in the base contract in case we need to add things in the future.
// This does not actually take up gas cost or storage cost, but it does reserve the storage slots.
// See OpenZeppelin's use of this pattern here:
// https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37
uint256[50] private __gap1;
uint256[50] private __gap2;
uint256[50] private __gap3;
uint256[50] private __gap4;
// solhint-disable-next-line func-name-mixedcase
function __BaseUpgradeablePausable__init(address owner) public initializer {
require(owner != address(0), "Owner cannot be the zero address");
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
library StakingRewardsVesting {
using SafeMath for uint256;
using StakingRewardsVesting for Rewards;
uint256 internal constant PERCENTAGE_DECIMALS = 1e18;
struct Rewards {
uint256 totalUnvested;
uint256 totalVested;
uint256 totalPreviouslyVested;
uint256 totalClaimed;
uint256 startTime;
uint256 endTime;
}
function claim(Rewards storage rewards, uint256 reward) internal {
rewards.totalClaimed = rewards.totalClaimed.add(reward);
}
function claimable(Rewards storage rewards) internal view returns (uint256) {
return rewards.totalVested.add(rewards.totalPreviouslyVested).sub(rewards.totalClaimed);
}
function currentGrant(Rewards storage rewards) internal view returns (uint256) {
return rewards.totalUnvested.add(rewards.totalVested);
}
/// @notice Slash the vesting rewards by `percentage`. `percentage` of the unvested portion
/// of the grant is forfeited. The remaining unvested portion continues to vest over the rest
/// of the vesting schedule. The already vested portion continues to be claimable.
///
/// A motivating example:
///
/// Let's say we're 50% through vesting, with 100 tokens granted. Thus, 50 tokens are vested and 50 are unvested.
/// Now let's say the grant is slashed by 90% (e.g. for StakingRewards, because the user unstaked 90% of their
/// position). 45 of the unvested tokens will be forfeited. 5 of the unvested tokens and 5 of the vested tokens
/// will be considered as the "new grant", which is 50% through vesting. The remaining 45 vested tokens will be
/// still be claimable at any time.
function slash(Rewards storage rewards, uint256 percentage) internal {
require(percentage <= PERCENTAGE_DECIMALS, "slashing percentage cannot be greater than 100%");
uint256 unvestedToSlash = rewards.totalUnvested.mul(percentage).div(PERCENTAGE_DECIMALS);
uint256 vestedToMove = rewards.totalVested.mul(percentage).div(PERCENTAGE_DECIMALS);
rewards.totalUnvested = rewards.totalUnvested.sub(unvestedToSlash);
rewards.totalVested = rewards.totalVested.sub(vestedToMove);
rewards.totalPreviouslyVested = rewards.totalPreviouslyVested.add(vestedToMove);
}
function checkpoint(Rewards storage rewards) internal {
uint256 newTotalVested = totalVestedAt(rewards.startTime, rewards.endTime, block.timestamp, rewards.currentGrant());
if (newTotalVested > rewards.totalVested) {
uint256 difference = newTotalVested.sub(rewards.totalVested);
rewards.totalUnvested = rewards.totalUnvested.sub(difference);
rewards.totalVested = newTotalVested;
}
}
function totalVestedAt(
uint256 start,
uint256 end,
uint256 time,
uint256 grantedAmount
) internal pure returns (uint256) {
if (end <= start) {
return grantedAmount;
}
return Math.min(grantedAmount.mul(time.sub(start)).div(end.sub(start)), grantedAmount);
}
}
pragma solidity ^0.6.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.12;
pragma experimental ABIEncoderV2;
import "./IV2CreditLine.sol";
abstract contract ITranchedPool {
IV2CreditLine public creditLine;
uint256 public createdAt;
enum Tranches {
Reserved,
Senior,
Junior
}
struct TrancheInfo {
uint256 id;
uint256 principalDeposited;
uint256 principalSharePrice;
uint256 interestSharePrice;
uint256 lockedUntil;
}
struct PoolSlice {
TrancheInfo seniorTranche;
TrancheInfo juniorTranche;
uint256 totalInterestAccrued;
uint256 principalDeployed;
}
struct SliceInfo {
uint256 reserveFeePercent;
uint256 interestAccrued;
uint256 principalAccrued;
}
struct ApplyResult {
uint256 interestRemaining;
uint256 principalRemaining;
uint256 reserveDeduction;
uint256 oldInterestSharePrice;
uint256 oldPrincipalSharePrice;
}
function initialize(
address _config,
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) public virtual;
function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory);
function pay(uint256 amount) external virtual;
function lockJuniorCapital() external virtual;
function lockPool() external virtual;
function initializeNextSlice(uint256 _fundableAt) external virtual;
function totalJuniorDeposits() external view virtual returns (uint256);
function drawdown(uint256 amount) external virtual;
function setFundableAt(uint256 timestamp) external virtual;
function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId);
function assess() external virtual;
function depositWithPermit(
uint256 tranche,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual returns (uint256 tokenId);
function availableToWithdraw(uint256 tokenId)
external
view
virtual
returns (uint256 interestRedeemable, uint256 principalRedeemable);
function withdraw(uint256 tokenId, uint256 amount)
external
virtual
returns (uint256 interestWithdrawn, uint256 principalWithdrawn);
function withdrawMax(uint256 tokenId)
external
virtual
returns (uint256 interestWithdrawn, uint256 principalWithdrawn);
function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ICreditLine.sol";
abstract contract IV2CreditLine is ICreditLine {
function principal() external view virtual returns (uint256);
function totalInterestAccrued() external view virtual returns (uint256);
function termStartTime() external view virtual returns (uint256);
function setLimit(uint256 newAmount) external virtual;
function setMaxLimit(uint256 newAmount) external virtual;
function setBalance(uint256 newBalance) external virtual;
function setPrincipal(uint256 _principal) external virtual;
function setTotalInterestAccrued(uint256 _interestAccrued) external virtual;
function drawdown(uint256 amount) external virtual;
function assess()
external
virtual
returns (
uint256,
uint256,
uint256
);
function initialize(
address _config,
address owner,
address _borrower,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) public virtual;
function setTermEndTime(uint256 newTermEndTime) external virtual;
function setNextDueTime(uint256 newNextDueTime) external virtual;
function setInterestOwed(uint256 newInterestOwed) external virtual;
function setPrincipalOwed(uint256 newPrincipalOwed) external virtual;
function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual;
function setWritedownAmount(uint256 newWritedownAmount) external virtual;
function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual;
function setLateFeeApr(uint256 newLateFeeApr) external virtual;
function updateGoldfinchConfig() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface ICreditLine {
function borrower() external view returns (address);
function limit() external view returns (uint256);
function maxLimit() external view returns (uint256);
function interestApr() external view returns (uint256);
function paymentPeriodInDays() external view returns (uint256);
function principalGracePeriodInDays() external view returns (uint256);
function termInDays() external view returns (uint256);
function lateFeeApr() external view returns (uint256);
function isLate() external view returns (bool);
function withinPrincipalGracePeriod() external view returns (bool);
// Accounting variables
function balance() external view returns (uint256);
function interestOwed() external view returns (uint256);
function principalOwed() external view returns (uint256);
function termEndTime() external view returns (uint256);
function nextDueTime() external view returns (uint256);
function interestAccruedAsOf() external view returns (uint256);
function lastFullPaymentTime() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IGoldfinchConfig {
function getNumber(uint256 index) external returns (uint256);
function getAddress(uint256 index) external returns (address);
function setAddress(uint256 index, address newAddress) external returns (address);
function setNumber(uint256 index, uint256 newNumber) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @title ConfigOptions
* @notice A central place for enumerating the configurable options of our GoldfinchConfig contract
* @author Goldfinch
*/
library ConfigOptions {
// NEVER EVER CHANGE THE ORDER OF THESE!
// You can rename or append. But NEVER change the order.
enum Numbers {
TransactionLimit,
TotalFundsLimit,
MaxUnderwriterLimit,
ReserveDenominator,
WithdrawFeeDenominator,
LatenessGracePeriodInDays,
LatenessMaxDays,
DrawdownPeriodInSeconds,
TransferRestrictionPeriodInDays,
LeverageRatio
}
enum Addresses {
Pool,
CreditLineImplementation,
GoldfinchFactory,
CreditDesk,
Fidu,
USDC,
TreasuryReserve,
ProtocolAdmin,
OneInch,
TrustedForwarder,
CUSDCContract,
GoldfinchConfig,
PoolTokens,
TranchedPoolImplementation,
SeniorPool,
SeniorPoolStrategy,
MigratedTranchedPoolImplementation,
BorrowerImplementation,
GFI,
Go,
BackerRewards,
StakingRewards
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
/**
* @title PauserPausable
* @notice Inheriting from OpenZeppelin's Pausable contract, this does small
* augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract.
* It is meant to be inherited.
* @author Goldfinch
*/
contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// solhint-disable-next-line func-name-mixedcase
function __PauserPausable__init() public initializer {
__Pausable_init_unchained();
}
/**
* @dev Pauses all functions guarded by Pause
*
* See {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the PAUSER_ROLE.
*/
function pause() public onlyPauserRole {
_pause();
}
/**
* @dev Unpauses the contract
*
* See {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the Pauser role
*/
function unpause() public onlyPauserRole {
_unpause();
}
modifier onlyPauserRole() {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IPool {
uint256 public sharePrice;
function deposit(uint256 amount) external virtual;
function withdraw(uint256 usdcAmount) external virtual;
function withdrawInFidu(uint256 fiduAmount) external virtual;
function collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) public virtual;
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool);
function drawdown(address to, uint256 amount) public virtual returns (bool);
function sweepToCompound() public virtual;
function sweepFromCompound() public virtual;
function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual;
function assets() public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IERC20withDec.sol";
interface IFidu is IERC20withDec {
function mintTo(address to, uint256 amount) external;
function burnFrom(address to, uint256 amount) external;
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ISeniorPool.sol";
import "./ITranchedPool.sol";
abstract contract ISeniorPoolStrategy {
function getLeverageRatio(ITranchedPool pool) public view virtual returns (uint256);
function invest(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256 amount);
function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract ICreditDesk {
uint256 public totalWritedowns;
uint256 public totalLoansOutstanding;
function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual;
function drawdown(address creditLineAddress, uint256 amount) external virtual;
function pay(address creditLineAddress, uint256 amount) external virtual;
function assessCreditLine(address creditLineAddress) external virtual;
function applyPayment(address creditLineAddress, uint256 amount) external virtual;
function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock) external view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
// Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IERC20withDec.sol";
interface ICUSDCContract is IERC20withDec {
/*** User Interface ***/
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function balanceOfUnderlying(address owner) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
/*** Admin Functions ***/
function _addReserves(uint256 addAmount) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol";
interface IPoolTokens is IERC721 {
event TokenMinted(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 amount,
uint256 tranche
);
event TokenRedeemed(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed,
uint256 tranche
);
event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);
struct TokenInfo {
address pool;
uint256 tranche;
uint256 principalAmount;
uint256 principalRedeemed;
uint256 interestRedeemed;
}
struct MintParams {
uint256 principalAmount;
uint256 tranche;
}
function mint(MintParams calldata params, address to) external returns (uint256);
function redeem(
uint256 tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed
) external;
function burn(uint256 tokenId) external;
function onPoolCreated(address newPool) external;
function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory);
function validPool(address sender) external view returns (bool);
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IBackerRewards {
function allocateRewards(uint256 _interestPaymentAmount) external;
function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IGoldfinchFactory {
function createCreditLine() external returns (address);
function createBorrower(address owner) external returns (address);
function createPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256[] calldata _allowedUIDTypes
) external returns (address);
function createMigratedPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256[] calldata _allowedUIDTypes
) external returns (address);
function updateGoldfinchConfig() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IGo {
uint256 public constant ID_TYPE_0 = 0;
uint256 public constant ID_TYPE_1 = 1;
uint256 public constant ID_TYPE_2 = 2;
uint256 public constant ID_TYPE_3 = 3;
uint256 public constant ID_TYPE_4 = 4;
uint256 public constant ID_TYPE_5 = 5;
uint256 public constant ID_TYPE_6 = 6;
uint256 public constant ID_TYPE_7 = 7;
uint256 public constant ID_TYPE_8 = 8;
uint256 public constant ID_TYPE_9 = 9;
uint256 public constant ID_TYPE_10 = 10;
/// @notice Returns the address of the UniqueIdentity contract.
function uniqueIdentity() external virtual returns (address);
function go(address account) public view virtual returns (bool);
function goOnlyIdTypes(address account, uint256[] calldata onlyIdTypes) public view virtual returns (bool);
function goSeniorPool(address account) public view virtual returns (bool);
function updateGoldfinchConfig() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../protocol/core/Pool.sol";
import "../protocol/core/Accountant.sol";
import "../protocol/core/CreditLine.sol";
import "../protocol/core/GoldfinchConfig.sol";
contract FakeV2CreditDesk is BaseUpgradeablePausable {
uint256 public totalWritedowns;
uint256 public totalLoansOutstanding;
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
GoldfinchConfig public config;
struct Underwriter {
uint256 governanceLimit;
address[] creditLines;
}
struct Borrower {
address[] creditLines;
}
event PaymentMade(
address indexed payer,
address indexed creditLine,
uint256 interestAmount,
uint256 principalAmount,
uint256 remainingAmount
);
event PrepaymentMade(address indexed payer, address indexed creditLine, uint256 prepaymentAmount);
event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount);
event CreditLineCreated(address indexed borrower, address indexed creditLine);
event PoolAddressUpdated(address indexed oldAddress, address indexed newAddress);
event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit);
event LimitChanged(address indexed owner, string limitType, uint256 amount);
mapping(address => Underwriter) public underwriters;
mapping(address => Borrower) private borrowers;
function initialize(address owner, GoldfinchConfig _config) public initializer {
owner;
_config;
return;
}
function someBrandNewFunction() public pure returns (uint256) {
return 5;
}
function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) {
return underwriters[underwriterAddress].creditLines;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
/**
* @title Goldfinch's Pool contract
* @notice Main entry point for LP's (a.k.a. capital providers)
* Handles key logic for depositing and withdrawing funds from the Pool
* @author Goldfinch
*/
contract Pool is BaseUpgradeablePausable, IPool {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
uint256 public compoundBalance;
event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares);
event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount);
event TransferMade(address indexed from, address indexed to, uint256 amount);
event InterestCollected(address indexed payer, uint256 poolAmount, uint256 reserveAmount);
event PrincipalCollected(address indexed payer, uint256 amount);
event ReserveFundsCollected(address indexed user, uint256 amount);
event PrincipalWrittendown(address indexed creditline, int256 amount);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/**
* @notice Run only once, on initialization
* @param owner The address of who should have the "OWNER_ROLE" of this contract
* @param _config The address of the GoldfinchConfig contract
*/
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
sharePrice = fiduMantissa();
IERC20withDec usdc = config.getUSDC();
// Sanity check the address
usdc.totalSupply();
// Unlock self for infinite amount
bool success = usdc.approve(address(this), uint256(-1));
require(success, "Failed to approve USDC");
}
/**
* @notice Deposits `amount` USDC from msg.sender into the Pool, and returns you the equivalent value of FIDU tokens
* @param amount The amount of USDC to deposit
*/
function deposit(uint256 amount) external override whenNotPaused withinTransactionLimit(amount) nonReentrant {
require(amount > 0, "Must deposit more than zero");
// Check if the amount of new shares to be added is within limits
uint256 depositShares = getNumShares(amount);
uint256 potentialNewTotalShares = totalShares().add(depositShares);
require(poolWithinLimit(potentialNewTotalShares), "Deposit would put the Pool over the total limit.");
emit DepositMade(msg.sender, amount, depositShares);
bool success = doUSDCTransfer(msg.sender, address(this), amount);
require(success, "Failed to transfer for deposit");
config.getFidu().mintTo(msg.sender, depositShares);
}
/**
* @notice Withdraws USDC from the Pool to msg.sender, and burns the equivalent value of FIDU tokens
* @param usdcAmount The amount of USDC to withdraw
*/
function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant {
require(usdcAmount > 0, "Must withdraw more than zero");
// This MUST happen before calculating withdrawShares, otherwise the share price
// changes between calculation and burning of Fidu, which creates a asset/liability mismatch
if (compoundBalance > 0) {
_sweepFromCompound();
}
uint256 withdrawShares = getNumShares(usdcAmount);
_withdraw(usdcAmount, withdrawShares);
}
/**
* @notice Withdraws USDC (denominated in FIDU terms) from the Pool to msg.sender
* @param fiduAmount The amount of USDC to withdraw in terms of fidu shares
*/
function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant {
require(fiduAmount > 0, "Must withdraw more than zero");
if (compoundBalance > 0) {
_sweepFromCompound();
}
uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount);
uint256 withdrawShares = fiduAmount;
_withdraw(usdcAmount, withdrawShares);
}
/**
* @notice Collects `interest` USDC in interest and `principal` in principal from `from` and sends it to the Pool.
* This also increases the share price accordingly. A portion is sent to the Goldfinch Reserve address
* @param from The address to take the USDC from. Implicitly, the Pool
* must be authorized to move USDC on behalf of `from`.
* @param interest the interest amount of USDC to move to the Pool
* @param principal the principal amount of USDC to move to the Pool
*
* Requirements:
* - The caller must be the Credit Desk. Not even the owner can call this function.
*/
function collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) public override onlyCreditDesk whenNotPaused {
_collectInterestAndPrincipal(from, interest, principal);
}
function distributeLosses(address creditlineAddress, int256 writedownDelta)
external
override
onlyCreditDesk
whenNotPaused
{
if (writedownDelta > 0) {
uint256 delta = usdcToSharePrice(uint256(writedownDelta));
sharePrice = sharePrice.add(delta);
} else {
// If delta is negative, convert to positive uint, and sub from sharePrice
uint256 delta = usdcToSharePrice(uint256(writedownDelta * -1));
sharePrice = sharePrice.sub(delta);
}
emit PrincipalWrittendown(creditlineAddress, writedownDelta);
}
/**
* @notice Moves `amount` USDC from `from`, to `to`.
* @param from The address to take the USDC from. Implicitly, the Pool
* must be authorized to move USDC on behalf of `from`.
* @param to The address that the USDC should be moved to
* @param amount the amount of USDC to move to the Pool
*
* Requirements:
* - The caller must be the Credit Desk. Not even the owner can call this function.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public override onlyCreditDesk whenNotPaused returns (bool) {
bool result = doUSDCTransfer(from, to, amount);
require(result, "USDC Transfer failed");
emit TransferMade(from, to, amount);
return result;
}
/**
* @notice Moves `amount` USDC from the pool, to `to`. This is similar to transferFrom except we sweep any
* balance we have from compound first and recognize interest. Meant to be called only by the credit desk on drawdown
* @param to The address that the USDC should be moved to
* @param amount the amount of USDC to move to the Pool
*
* Requirements:
* - The caller must be the Credit Desk. Not even the owner can call this function.
*/
function drawdown(address to, uint256 amount) public override onlyCreditDesk whenNotPaused returns (bool) {
if (compoundBalance > 0) {
_sweepFromCompound();
}
return transferFrom(address(this), to, amount);
}
function assets() public view override returns (uint256) {
ICreditDesk creditDesk = config.getCreditDesk();
return
compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(creditDesk.totalLoansOutstanding()).sub(
creditDesk.totalWritedowns()
);
}
function migrateToSeniorPool() external onlyAdmin {
// Bring back all USDC
if (compoundBalance > 0) {
sweepFromCompound();
}
// Pause deposits/withdrawals
if (!paused()) {
pause();
}
// Remove special priveldges from Fidu
bytes32 minterRole = keccak256("MINTER_ROLE");
bytes32 pauserRole = keccak256("PAUSER_ROLE");
config.getFidu().renounceRole(minterRole, address(this));
config.getFidu().renounceRole(pauserRole, address(this));
// Move all USDC to the SeniorPool
address seniorPoolAddress = config.seniorPoolAddress();
uint256 balance = config.getUSDC().balanceOf(address(this));
bool success = doUSDCTransfer(address(this), seniorPoolAddress, balance);
require(success, "Failed to transfer USDC balance to the senior pool");
// Claim our COMP!
address compoundController = address(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
bytes memory data = abi.encodeWithSignature("claimComp(address)", address(this));
bytes memory _res;
// solhint-disable-next-line avoid-low-level-calls
(success, _res) = compoundController.call(data);
require(success, "Failed to claim COMP");
// Send our balance of COMP!
address compToken = address(0xc00e94Cb662C3520282E6f5717214004A7f26888);
data = abi.encodeWithSignature("balanceOf(address)", address(this));
// solhint-disable-next-line avoid-low-level-calls
(success, _res) = compToken.call(data);
uint256 compBalance = toUint256(_res);
data = abi.encodeWithSignature("transfer(address,uint256)", seniorPoolAddress, compBalance);
// solhint-disable-next-line avoid-low-level-calls
(success, _res) = compToken.call(data);
require(success, "Failed to transfer COMP");
}
function toUint256(bytes memory _bytes) internal pure returns (uint256 value) {
assembly {
value := mload(add(_bytes, 0x20))
}
}
/**
* @notice Moves any USDC still in the Pool to Compound, and tracks the amount internally.
* This is done to earn interest on latent funds until we have other borrowers who can use it.
*
* Requirements:
* - The caller must be an admin.
*/
function sweepToCompound() public override onlyAdmin whenNotPaused {
IERC20 usdc = config.getUSDC();
uint256 usdcBalance = usdc.balanceOf(address(this));
ICUSDCContract cUSDC = config.getCUSDCContract();
// Approve compound to the exact amount
bool success = usdc.approve(address(cUSDC), usdcBalance);
require(success, "Failed to approve USDC for compound");
sweepToCompound(cUSDC, usdcBalance);
// Remove compound approval to be extra safe
success = config.getUSDC().approve(address(cUSDC), 0);
require(success, "Failed to approve USDC for compound");
}
/**
* @notice Moves any USDC from Compound back to the Pool, and recognizes interest earned.
* This is done automatically on drawdown or withdraw, but can be called manually if necessary.
*
* Requirements:
* - The caller must be an admin.
*/
function sweepFromCompound() public override onlyAdmin whenNotPaused {
_sweepFromCompound();
}
/* Internal Functions */
function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal withinTransactionLimit(usdcAmount) {
IFidu fidu = config.getFidu();
// Determine current shares the address has and the shares requested to withdraw
uint256 currentShares = fidu.balanceOf(msg.sender);
// Ensure the address has enough value in the pool
require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns");
uint256 reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator());
uint256 userAmount = usdcAmount.sub(reserveAmount);
emit WithdrawalMade(msg.sender, userAmount, reserveAmount);
// Send the amounts
bool success = doUSDCTransfer(address(this), msg.sender, userAmount);
require(success, "Failed to transfer for withdraw");
sendToReserve(address(this), reserveAmount, msg.sender);
// Burn the shares
fidu.burnFrom(msg.sender, withdrawShares);
}
function sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal {
// Our current design requires we re-normalize by withdrawing everything and recognizing interest gains
// before we can add additional capital to Compound
require(compoundBalance == 0, "Cannot sweep when we already have a compound balance");
require(usdcAmount != 0, "Amount to sweep cannot be zero");
uint256 error = cUSDC.mint(usdcAmount);
require(error == 0, "Sweep to compound failed");
compoundBalance = usdcAmount;
}
function sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal {
uint256 cBalance = compoundBalance;
require(cBalance != 0, "No funds on compound");
require(cUSDCAmount != 0, "Amount to sweep cannot be zero");
IERC20 usdc = config.getUSDC();
uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this));
uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent();
uint256 redeemedUSDC = cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount);
uint256 error = cUSDC.redeem(cUSDCAmount);
uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this));
require(error == 0, "Sweep from compound failed");
require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount");
uint256 interestAccrued = redeemedUSDC.sub(cBalance);
_collectInterestAndPrincipal(address(this), interestAccrued, 0);
compoundBalance = 0;
}
function _collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) internal {
uint256 reserveAmount = interest.div(config.getReserveDenominator());
uint256 poolAmount = interest.sub(reserveAmount);
uint256 increment = usdcToSharePrice(poolAmount);
sharePrice = sharePrice.add(increment);
if (poolAmount > 0) {
emit InterestCollected(from, poolAmount, reserveAmount);
}
if (principal > 0) {
emit PrincipalCollected(from, principal);
}
if (reserveAmount > 0) {
sendToReserve(from, reserveAmount, from);
}
// Gas savings: No need to transfer to yourself, which happens in sweepFromCompound
if (from != address(this)) {
bool success = doUSDCTransfer(from, address(this), principal.add(poolAmount));
require(success, "Failed to collect principal repayment");
}
}
function _sweepFromCompound() internal {
ICUSDCContract cUSDC = config.getCUSDCContract();
sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this)));
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function fiduMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(18);
}
function usdcMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(6);
}
function usdcToFidu(uint256 amount) internal pure returns (uint256) {
return amount.mul(fiduMantissa()).div(usdcMantissa());
}
function cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) {
// See https://compound.finance/docs#protocol-math
// But note, the docs and reality do not agree. Docs imply that that exchange rate is
// scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16
// 1e16 is also what Sheraz at Certik said.
uint256 usdcDecimals = 6;
uint256 cUSDCDecimals = 8;
// We multiply in the following order, for the following reasons...
// Amount in cToken (1e8)
// Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are)
// Downscale to cToken decimals (1e8)
// Downscale from cToken to USDC decimals (8 to 6)
return amount.mul(exchangeRate).div(10**(18 + usdcDecimals - cUSDCDecimals)).div(10**2);
}
function totalShares() internal view returns (uint256) {
return config.getFidu().totalSupply();
}
function usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) {
return usdcToFidu(usdcAmount).mul(fiduMantissa()).div(totalShares());
}
function poolWithinLimit(uint256 _totalShares) internal view returns (bool) {
return
_totalShares.mul(sharePrice).div(fiduMantissa()) <=
usdcToFidu(config.getNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit)));
}
function transactionWithinLimit(uint256 amount) internal view returns (bool) {
return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit));
}
function getNumShares(uint256 amount) internal view returns (uint256) {
return usdcToFidu(amount).mul(fiduMantissa()).div(sharePrice);
}
function getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) {
return fiduToUSDC(fiduAmount.mul(sharePrice).div(fiduMantissa()));
}
function fiduToUSDC(uint256 amount) internal pure returns (uint256) {
return amount.div(fiduMantissa().div(usdcMantissa()));
}
function sendToReserve(
address from,
uint256 amount,
address userForEvent
) internal {
emit ReserveFundsCollected(userForEvent, amount);
bool success = doUSDCTransfer(from, config.reserveAddress(), amount);
require(success, "Reserve transfer was not successful");
}
function doUSDCTransfer(
address from,
address to,
uint256 amount
) internal returns (bool) {
require(to != address(0), "Can't send to zero address");
IERC20withDec usdc = config.getUSDC();
return usdc.transferFrom(from, to, amount);
}
modifier withinTransactionLimit(uint256 amount) {
require(transactionWithinLimit(amount), "Amount is over the per-transaction limit");
_;
}
modifier onlyCreditDesk() {
require(msg.sender == config.creditDeskAddress(), "Only the credit desk is allowed to call this function");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./CreditLine.sol";
import "../../interfaces/ICreditLine.sol";
import "../../external/FixedPoint.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title The Accountant
* @notice Library for handling key financial calculations, such as interest and principal accrual.
* @author Goldfinch
*/
library Accountant {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Signed;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for int256;
using FixedPoint for uint256;
// Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled
uint256 public constant FP_SCALING_FACTOR = 10**18;
uint256 public constant INTEREST_DECIMALS = 1e18;
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
uint256 public constant SECONDS_PER_YEAR = (SECONDS_PER_DAY * 365);
struct PaymentAllocation {
uint256 interestPayment;
uint256 principalPayment;
uint256 additionalBalancePayment;
}
function calculateInterestAndPrincipalAccrued(
CreditLine cl,
uint256 timestamp,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
uint256 balance = cl.balance(); // gas optimization
uint256 interestAccrued = calculateInterestAccrued(cl, balance, timestamp, lateFeeGracePeriod);
uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, timestamp);
return (interestAccrued, principalAccrued);
}
function calculateInterestAndPrincipalAccruedOverPeriod(
CreditLine cl,
uint256 balance,
uint256 startTime,
uint256 endTime,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
uint256 interestAccrued = calculateInterestAccruedOverPeriod(cl, balance, startTime, endTime, lateFeeGracePeriod);
uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, endTime);
return (interestAccrued, principalAccrued);
}
function calculatePrincipalAccrued(
ICreditLine cl,
uint256 balance,
uint256 timestamp
) public view returns (uint256) {
// If we've already accrued principal as of the term end time, then don't accrue more principal
uint256 termEndTime = cl.termEndTime();
if (cl.interestAccruedAsOf() >= termEndTime) {
return 0;
}
if (timestamp >= termEndTime) {
return balance;
} else {
return 0;
}
}
function calculateWritedownFor(
ICreditLine cl,
uint256 timestamp,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
return calculateWritedownForPrincipal(cl, cl.balance(), timestamp, gracePeriodInDays, maxDaysLate);
}
function calculateWritedownForPrincipal(
ICreditLine cl,
uint256 principal,
uint256 timestamp,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl);
if (amountOwedPerDay.isEqual(0)) {
return (0, 0);
}
FixedPoint.Unsigned memory fpGracePeriod = FixedPoint.fromUnscaledUint(gracePeriodInDays);
FixedPoint.Unsigned memory daysLate;
// Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30,
// Before the term end date, we use the interestOwed to calculate the periods late. However, after the loan term
// has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to
// calculate the periods later.
uint256 totalOwed = cl.interestOwed().add(cl.principalOwed());
daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay);
if (timestamp > cl.termEndTime()) {
uint256 secondsLate = timestamp.sub(cl.termEndTime());
daysLate = daysLate.add(FixedPoint.fromUnscaledUint(secondsLate).div(SECONDS_PER_DAY));
}
FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate);
FixedPoint.Unsigned memory writedownPercent;
if (daysLate.isLessThanOrEqual(fpGracePeriod)) {
// Within the grace period, we don't have to write down, so assume 0%
writedownPercent = FixedPoint.fromUnscaledUint(0);
} else {
writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate));
}
FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(principal).div(FP_SCALING_FACTOR);
// This will return a number between 0-100 representing the write down percent with no decimals
uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue;
return (unscaledWritedownPercent, writedownAmount.rawValue);
}
function calculateAmountOwedForOneDay(ICreditLine cl) public view returns (FixedPoint.Unsigned memory interestOwed) {
// Determine theoretical interestOwed for one full day
uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS);
interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365);
return interestOwed;
}
function calculateInterestAccrued(
CreditLine cl,
uint256 balance,
uint256 timestamp,
uint256 lateFeeGracePeriodInDays
) public view returns (uint256) {
// We use Math.min here to prevent integer overflow (ie. go negative) when calculating
// numSecondsElapsed. Typically this shouldn't be possible, because
// the interestAccruedAsOf couldn't be *after* the current timestamp. However, when assessing
// we allow this function to be called with a past timestamp, which raises the possibility
// of overflow.
// This use of min should not generate incorrect interest calculations, since
// this function's purpose is just to normalize balances, and handing in a past timestamp
// will necessarily return zero interest accrued (because zero elapsed time), which is correct.
uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf());
return calculateInterestAccruedOverPeriod(cl, balance, startTime, timestamp, lateFeeGracePeriodInDays);
}
function calculateInterestAccruedOverPeriod(
CreditLine cl,
uint256 balance,
uint256 startTime,
uint256 endTime,
uint256 lateFeeGracePeriodInDays
) public view returns (uint256 interestOwed) {
uint256 secondsElapsed = endTime.sub(startTime);
uint256 totalInterestPerYear = balance.mul(cl.interestApr()).div(INTEREST_DECIMALS);
interestOwed = totalInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR);
if (lateFeeApplicable(cl, endTime, lateFeeGracePeriodInDays)) {
uint256 lateFeeInterestPerYear = balance.mul(cl.lateFeeApr()).div(INTEREST_DECIMALS);
uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR);
interestOwed = interestOwed.add(additionalLateFeeInterest);
}
return interestOwed;
}
function lateFeeApplicable(
CreditLine cl,
uint256 timestamp,
uint256 gracePeriodInDays
) public view returns (bool) {
uint256 secondsLate = timestamp.sub(cl.lastFullPaymentTime());
return cl.lateFeeApr() > 0 && secondsLate > gracePeriodInDays.mul(SECONDS_PER_DAY);
}
function allocatePayment(
uint256 paymentAmount,
uint256 balance,
uint256 interestOwed,
uint256 principalOwed
) public pure returns (PaymentAllocation memory) {
uint256 paymentRemaining = paymentAmount;
uint256 interestPayment = Math.min(interestOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(interestPayment);
uint256 principalPayment = Math.min(principalOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(principalPayment);
uint256 balanceRemaining = balance.sub(principalPayment);
uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining);
return
PaymentAllocation({
interestPayment: interestPayment,
principalPayment: principalPayment,
additionalBalancePayment: additionalBalancePayment
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "./ConfigHelper.sol";
import "./BaseUpgradeablePausable.sol";
import "./Accountant.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ICreditLine.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
/**
* @title CreditLine
* @notice A contract that represents the agreement between Backers and
* a Borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed.
* A CreditLine belongs to a TranchedPool, and is fully controlled by that TranchedPool. It does not
* operate in any standalone capacity. It should generally be considered internal to the TranchedPool.
* @author Goldfinch
*/
// solhint-disable-next-line max-states-count
contract CreditLine is BaseUpgradeablePausable, ICreditLine {
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
// Credit line terms
address public override borrower;
uint256 public currentLimit;
uint256 public override maxLimit;
uint256 public override interestApr;
uint256 public override paymentPeriodInDays;
uint256 public override termInDays;
uint256 public override principalGracePeriodInDays;
uint256 public override lateFeeApr;
// Accounting variables
uint256 public override balance;
uint256 public override interestOwed;
uint256 public override principalOwed;
uint256 public override termEndTime;
uint256 public override nextDueTime;
uint256 public override interestAccruedAsOf;
uint256 public override lastFullPaymentTime;
uint256 public totalInterestAccrued;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
function initialize(
address _config,
address owner,
address _borrower,
uint256 _maxLimit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) public initializer {
require(_config != address(0) && owner != address(0) && _borrower != address(0), "Zero address passed in");
__BaseUpgradeablePausable__init(owner);
config = GoldfinchConfig(_config);
borrower = _borrower;
maxLimit = _maxLimit;
interestApr = _interestApr;
paymentPeriodInDays = _paymentPeriodInDays;
termInDays = _termInDays;
lateFeeApr = _lateFeeApr;
principalGracePeriodInDays = _principalGracePeriodInDays;
interestAccruedAsOf = block.timestamp;
// Unlock owner, which is a TranchedPool, for infinite amount
bool success = config.getUSDC().approve(owner, uint256(-1));
require(success, "Failed to approve USDC");
}
function limit() external view override returns (uint256) {
return currentLimit;
}
/**
* @notice Updates the internal accounting to track a drawdown as of current block timestamp.
* Does not move any money
* @param amount The amount in USDC that has been drawndown
*/
function drawdown(uint256 amount) external onlyAdmin {
require(amount.add(balance) <= currentLimit, "Cannot drawdown more than the limit");
require(amount > 0, "Invalid drawdown amount");
uint256 timestamp = currentTime();
if (balance == 0) {
setInterestAccruedAsOf(timestamp);
setLastFullPaymentTime(timestamp);
setTotalInterestAccrued(0);
setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays)));
}
(uint256 _interestOwed, uint256 _principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp);
balance = balance.add(amount);
updateCreditLineAccounting(balance, _interestOwed, _principalOwed);
require(!_isLate(timestamp), "Cannot drawdown when payments are past due");
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function setLateFeeApr(uint256 newLateFeeApr) external onlyAdmin {
lateFeeApr = newLateFeeApr;
}
function setLimit(uint256 newAmount) external onlyAdmin {
require(newAmount <= maxLimit, "Cannot be more than the max limit");
currentLimit = newAmount;
}
function setMaxLimit(uint256 newAmount) external onlyAdmin {
maxLimit = newAmount;
}
function termStartTime() external view returns (uint256) {
return _termStartTime();
}
function isLate() external view override returns (bool) {
return _isLate(block.timestamp);
}
function withinPrincipalGracePeriod() external view override returns (bool) {
if (termEndTime == 0) {
// Loan hasn't started yet
return true;
}
return block.timestamp < _termStartTime().add(principalGracePeriodInDays.mul(SECONDS_PER_DAY));
}
function setTermEndTime(uint256 newTermEndTime) public onlyAdmin {
termEndTime = newTermEndTime;
}
function setNextDueTime(uint256 newNextDueTime) public onlyAdmin {
nextDueTime = newNextDueTime;
}
function setBalance(uint256 newBalance) public onlyAdmin {
balance = newBalance;
}
function setTotalInterestAccrued(uint256 _totalInterestAccrued) public onlyAdmin {
totalInterestAccrued = _totalInterestAccrued;
}
function setInterestOwed(uint256 newInterestOwed) public onlyAdmin {
interestOwed = newInterestOwed;
}
function setPrincipalOwed(uint256 newPrincipalOwed) public onlyAdmin {
principalOwed = newPrincipalOwed;
}
function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) public onlyAdmin {
interestAccruedAsOf = newInterestAccruedAsOf;
}
function setLastFullPaymentTime(uint256 newLastFullPaymentTime) public onlyAdmin {
lastFullPaymentTime = newLastFullPaymentTime;
}
/**
* @notice Triggers an assessment of the creditline. Any USDC balance available in the creditline is applied
* towards the interest and principal.
* @return Any amount remaining after applying payments towards the interest and principal
* @return Amount applied towards interest
* @return Amount applied towards principal
*/
function assess()
public
onlyAdmin
returns (
uint256,
uint256,
uint256
)
{
// Do not assess until a full period has elapsed or past due
require(balance > 0, "Must have balance to assess credit line");
// Don't assess credit lines early!
if (currentTime() < nextDueTime && !_isLate(currentTime())) {
return (0, 0, 0);
}
uint256 timeToAssess = calculateNextDueTime();
setNextDueTime(timeToAssess);
// We always want to assess for the most recently *past* nextDueTime.
// So if the recalculation above sets the nextDueTime into the future,
// then ensure we pass in the one just before this.
if (timeToAssess > currentTime()) {
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
timeToAssess = timeToAssess.sub(secondsPerPeriod);
}
return handlePayment(getUSDCBalance(address(this)), timeToAssess);
}
function calculateNextDueTime() internal view returns (uint256) {
uint256 newNextDueTime = nextDueTime;
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
uint256 curTimestamp = currentTime();
// You must have just done your first drawdown
if (newNextDueTime == 0 && balance > 0) {
return curTimestamp.add(secondsPerPeriod);
}
// Active loan that has entered a new period, so return the *next* newNextDueTime.
// But never return something after the termEndTime
if (balance > 0 && curTimestamp >= newNextDueTime) {
uint256 secondsToAdvance = (curTimestamp.sub(newNextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod);
newNextDueTime = newNextDueTime.add(secondsToAdvance);
return Math.min(newNextDueTime, termEndTime);
}
// You're paid off, or have not taken out a loan yet, so no next due time.
if (balance == 0 && newNextDueTime != 0) {
return 0;
}
// Active loan in current period, where we've already set the newNextDueTime correctly, so should not change.
if (balance > 0 && curTimestamp < newNextDueTime) {
return newNextDueTime;
}
revert("Error: could not calculate next due time.");
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function _isLate(uint256 timestamp) internal view returns (bool) {
uint256 secondsElapsedSinceFullPayment = timestamp.sub(lastFullPaymentTime);
return balance > 0 && secondsElapsedSinceFullPayment > paymentPeriodInDays.mul(SECONDS_PER_DAY);
}
function _termStartTime() internal view returns (uint256) {
return termEndTime.sub(SECONDS_PER_DAY.mul(termInDays));
}
/**
* @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool.
* It also updates all the accounting variables. Note that interest is always paid back first, then principal.
* Any extra after paying the minimum will go towards existing principal (reducing the
* effective interest rate). Any extra after the full loan has been paid off will remain in the
* USDC Balance of the creditLine, where it will be automatically used for the next drawdown.
* @param paymentAmount The amount, in USDC atomic units, to be applied
* @param timestamp The timestamp on which accrual calculations should be based. This allows us
* to be precise when we assess a Credit Line
*/
function handlePayment(uint256 paymentAmount, uint256 timestamp)
internal
returns (
uint256,
uint256,
uint256
)
{
(uint256 newInterestOwed, uint256 newPrincipalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp);
Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(
paymentAmount,
balance,
newInterestOwed,
newPrincipalOwed
);
uint256 newBalance = balance.sub(pa.principalPayment);
// Apply any additional payment towards the balance
newBalance = newBalance.sub(pa.additionalBalancePayment);
uint256 totalPrincipalPayment = balance.sub(newBalance);
uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment);
updateCreditLineAccounting(
newBalance,
newInterestOwed.sub(pa.interestPayment),
newPrincipalOwed.sub(pa.principalPayment)
);
assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount);
return (paymentRemaining, pa.interestPayment, totalPrincipalPayment);
}
function updateAndGetInterestAndPrincipalOwedAsOf(uint256 timestamp) internal returns (uint256, uint256) {
(uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
this,
timestamp,
config.getLatenessGracePeriodInDays()
);
if (interestAccrued > 0) {
// If we've accrued any interest, update interestAccruedAsOf to the time that we've
// calculated interest for. If we've not accrued any interest, then we keep the old value so the next
// time the entire period is taken into account.
setInterestAccruedAsOf(timestamp);
totalInterestAccrued = totalInterestAccrued.add(interestAccrued);
}
return (interestOwed.add(interestAccrued), principalOwed.add(principalAccrued));
}
function updateCreditLineAccounting(
uint256 newBalance,
uint256 newInterestOwed,
uint256 newPrincipalOwed
) internal nonReentrant {
setBalance(newBalance);
setInterestOwed(newInterestOwed);
setPrincipalOwed(newPrincipalOwed);
// This resets lastFullPaymentTime. These conditions assure that they have
// indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown)
uint256 _nextDueTime = nextDueTime;
if (newInterestOwed == 0 && _nextDueTime != 0) {
// If interest was fully paid off, then set the last full payment as the previous due time
uint256 mostRecentLastDueTime;
if (currentTime() < _nextDueTime) {
uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);
mostRecentLastDueTime = _nextDueTime.sub(secondsPerPeriod);
} else {
mostRecentLastDueTime = _nextDueTime;
}
setLastFullPaymentTime(mostRecentLastDueTime);
}
setNextDueTime(calculateNextDueTime());
}
function getUSDCBalance(address _address) internal view returns (uint256) {
return config.getUSDC().balanceOf(_address);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
// solhint-disable
// Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5**18`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on 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 Integer division of two signed integers truncating the quotient, reverts on division by 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 Subtracts two signed integers, reverts on 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 Adds two signed integers, reverts on 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.12;
pragma experimental ABIEncoderV2;
import "../interfaces/IERC20withDec.sol";
import "../protocol/core/GoldfinchConfig.sol";
import "../protocol/core/ConfigHelper.sol";
import "../protocol/core/TranchedPool.sol";
contract TestTranchedPool is TranchedPool {
function _collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) public {
collectInterestAndPrincipal(from, interest, principal);
}
function _setSeniorTranchePrincipalDeposited(uint256 principalDeposited) public {
poolSlices[poolSlices.length - 1].seniorTranche.principalDeposited = principalDeposited;
}
function _setLimit(uint256 limit) public {
creditLine.setLimit(limit);
}
function _modifyJuniorTrancheLockedUntil(uint256 lockedUntil) public {
poolSlices[poolSlices.length - 1].juniorTranche.lockedUntil = lockedUntil;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/IV2CreditLine.sol";
import "../../interfaces/IPoolTokens.sol";
import "./GoldfinchConfig.sol";
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "../../library/SafeERC20Transfer.sol";
import "./TranchingLogic.sol";
contract TranchedPool is BaseUpgradeablePausable, ITranchedPool, SafeERC20Transfer {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
using TranchingLogic for PoolSlice;
using TranchingLogic for TrancheInfo;
bytes32 public constant LOCKER_ROLE = keccak256("LOCKER_ROLE");
bytes32 public constant SENIOR_ROLE = keccak256("SENIOR_ROLE");
uint256 public constant FP_SCALING_FACTOR = 1e18;
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
uint256 public constant ONE_HUNDRED = 100; // Need this because we cannot call .div on a literal 100
uint256 public constant NUM_TRANCHES_PER_SLICE = 2;
uint256 public juniorFeePercent;
bool public drawdownsPaused;
uint256[] public allowedUIDTypes;
uint256 public totalDeployed;
uint256 public fundableAt;
PoolSlice[] public poolSlices;
event DepositMade(address indexed owner, uint256 indexed tranche, uint256 indexed tokenId, uint256 amount);
event WithdrawalMade(
address indexed owner,
uint256 indexed tranche,
uint256 indexed tokenId,
uint256 interestWithdrawn,
uint256 principalWithdrawn
);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
event TranchedPoolAssessed(address indexed pool);
event PaymentApplied(
address indexed payer,
address indexed pool,
uint256 interestAmount,
uint256 principalAmount,
uint256 remainingAmount,
uint256 reserveAmount
);
// Note: This has to exactly match the even in the TranchingLogic library for events to be emitted
// correctly
event SharePriceUpdated(
address indexed pool,
uint256 indexed tranche,
uint256 principalSharePrice,
int256 principalDelta,
uint256 interestSharePrice,
int256 interestDelta
);
event ReserveFundsCollected(address indexed from, uint256 amount);
event CreditLineMigrated(address indexed oldCreditLine, address indexed newCreditLine);
event DrawdownMade(address indexed borrower, uint256 amount);
event DrawdownsPaused(address indexed pool);
event DrawdownsUnpaused(address indexed pool);
event EmergencyShutdown(address indexed pool);
event TrancheLocked(address indexed pool, uint256 trancheId, uint256 lockedUntil);
event SliceCreated(address indexed pool, uint256 sliceId);
function initialize(
address _config,
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) public override initializer {
require(address(_config) != address(0) && address(_borrower) != address(0), "Config/borrower invalid");
config = GoldfinchConfig(_config);
address owner = config.protocolAdminAddress();
require(owner != address(0), "Owner invalid");
__BaseUpgradeablePausable__init(owner);
_initializeNextSlice(_fundableAt);
createAndSetCreditLine(
_borrower,
_limit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays
);
createdAt = block.timestamp;
juniorFeePercent = _juniorFeePercent;
if (_allowedUIDTypes.length == 0) {
uint256[1] memory defaultAllowedUIDTypes = [config.getGo().ID_TYPE_0()];
allowedUIDTypes = defaultAllowedUIDTypes;
} else {
allowedUIDTypes = _allowedUIDTypes;
}
_setupRole(LOCKER_ROLE, _borrower);
_setupRole(LOCKER_ROLE, owner);
_setRoleAdmin(LOCKER_ROLE, OWNER_ROLE);
_setRoleAdmin(SENIOR_ROLE, OWNER_ROLE);
// Give the senior pool the ability to deposit into the senior pool
_setupRole(SENIOR_ROLE, address(config.getSeniorPool()));
// Unlock self for infinite amount
bool success = config.getUSDC().approve(address(this), uint256(-1));
require(success, "Failed to approve USDC");
}
function setAllowedUIDTypes(uint256[] calldata ids) public onlyLocker {
require(
poolSlices[0].juniorTranche.principalDeposited == 0 && poolSlices[0].seniorTranche.principalDeposited == 0,
"Must not have balance"
);
allowedUIDTypes = ids;
}
/**
* @notice Deposit a USDC amount into the pool for a tranche. Mints an NFT to the caller representing the position
* @param tranche The number representing the tranche to deposit into
* @param amount The USDC amount to tranfer from the caller to the pool
* @return tokenId The tokenId of the NFT
*/
function deposit(uint256 tranche, uint256 amount)
public
override
nonReentrant
whenNotPaused
returns (uint256 tokenId)
{
TrancheInfo storage trancheInfo = getTrancheInfo(tranche);
require(trancheInfo.lockedUntil == 0, "Tranche locked");
require(amount > 0, "Must deposit > zero");
require(config.getGo().goOnlyIdTypes(msg.sender, allowedUIDTypes), "Address not go-listed");
require(block.timestamp > fundableAt, "Not open for funding");
// senior tranche ids are always odd numbered
if (_isSeniorTrancheId(trancheInfo.id)) {
require(hasRole(SENIOR_ROLE, _msgSender()), "Req SENIOR_ROLE");
}
trancheInfo.principalDeposited = trancheInfo.principalDeposited.add(amount);
IPoolTokens.MintParams memory params = IPoolTokens.MintParams({tranche: tranche, principalAmount: amount});
tokenId = config.getPoolTokens().mint(params, msg.sender);
safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount);
emit DepositMade(msg.sender, tranche, tokenId, amount);
return tokenId;
}
function depositWithPermit(
uint256 tranche,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public override returns (uint256 tokenId) {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
return deposit(tranche, amount);
}
/**
* @notice Withdraw an already deposited amount if the funds are available
* @param tokenId The NFT representing the position
* @param amount The amount to withdraw (must be <= interest+principal currently available to withdraw)
* @return interestWithdrawn The interest amount that was withdrawn
* @return principalWithdrawn The principal amount that was withdrawn
*/
function withdraw(uint256 tokenId, uint256 amount)
public
override
nonReentrant
whenNotPaused
returns (uint256 interestWithdrawn, uint256 principalWithdrawn)
{
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche);
return _withdraw(trancheInfo, tokenInfo, tokenId, amount);
}
/**
* @notice Withdraw from many tokens (that the sender owns) in a single transaction
* @param tokenIds An array of tokens ids representing the position
* @param amounts An array of amounts to withdraw from the corresponding tokenIds
*/
function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) public override {
require(tokenIds.length == amounts.length, "TokensIds and Amounts mismatch");
for (uint256 i = 0; i < amounts.length; i++) {
withdraw(tokenIds[i], amounts[i]);
}
}
/**
* @notice Similar to withdraw but will withdraw all available funds
* @param tokenId The NFT representing the position
* @return interestWithdrawn The interest amount that was withdrawn
* @return principalWithdrawn The principal amount that was withdrawn
*/
function withdrawMax(uint256 tokenId)
external
override
nonReentrant
whenNotPaused
returns (uint256 interestWithdrawn, uint256 principalWithdrawn)
{
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche);
(uint256 interestRedeemable, uint256 principalRedeemable) = redeemableInterestAndPrincipal(trancheInfo, tokenInfo);
uint256 amount = interestRedeemable.add(principalRedeemable);
return _withdraw(trancheInfo, tokenInfo, tokenId, amount);
}
/**
* @notice Draws down the funds (and locks the pool) to the borrower address. Can only be called by the borrower
* @param amount The amount to drawdown from the creditline (must be < limit)
*/
function drawdown(uint256 amount) external override onlyLocker whenNotPaused {
require(!drawdownsPaused, "Drawdowns are paused");
if (!locked()) {
// Assumes the senior pool has invested already (saves the borrower a separate transaction to lock the pool)
_lockPool();
}
// Drawdown only draws down from the current slice for simplicity. It's harder to account for how much
// money is available from previous slices since depositors can redeem after unlock.
PoolSlice storage currentSlice = poolSlices[poolSlices.length.sub(1)];
uint256 amountAvailable = sharePriceToUsdc(
currentSlice.juniorTranche.principalSharePrice,
currentSlice.juniorTranche.principalDeposited
);
amountAvailable = amountAvailable.add(
sharePriceToUsdc(currentSlice.seniorTranche.principalSharePrice, currentSlice.seniorTranche.principalDeposited)
);
require(amount <= amountAvailable, "Insufficient funds in slice");
creditLine.drawdown(amount);
// Update the share price to reflect the amount remaining in the pool
uint256 amountRemaining = amountAvailable.sub(amount);
uint256 oldJuniorPrincipalSharePrice = currentSlice.juniorTranche.principalSharePrice;
uint256 oldSeniorPrincipalSharePrice = currentSlice.seniorTranche.principalSharePrice;
currentSlice.juniorTranche.principalSharePrice = currentSlice.juniorTranche.calculateExpectedSharePrice(
amountRemaining,
currentSlice
);
currentSlice.seniorTranche.principalSharePrice = currentSlice.seniorTranche.calculateExpectedSharePrice(
amountRemaining,
currentSlice
);
currentSlice.principalDeployed = currentSlice.principalDeployed.add(amount);
totalDeployed = totalDeployed.add(amount);
address borrower = creditLine.borrower();
safeERC20TransferFrom(config.getUSDC(), address(this), borrower, amount);
emit DrawdownMade(borrower, amount);
emit SharePriceUpdated(
address(this),
currentSlice.juniorTranche.id,
currentSlice.juniorTranche.principalSharePrice,
int256(oldJuniorPrincipalSharePrice.sub(currentSlice.juniorTranche.principalSharePrice)) * -1,
currentSlice.juniorTranche.interestSharePrice,
0
);
emit SharePriceUpdated(
address(this),
currentSlice.seniorTranche.id,
currentSlice.seniorTranche.principalSharePrice,
int256(oldSeniorPrincipalSharePrice.sub(currentSlice.seniorTranche.principalSharePrice)) * -1,
currentSlice.seniorTranche.interestSharePrice,
0
);
}
/**
* @notice Locks the junior tranche, preventing more junior deposits. Gives time for the senior to determine how
* much to invest (ensure leverage ratio cannot change for the period)
*/
function lockJuniorCapital() external override onlyLocker whenNotPaused {
_lockJuniorCapital(poolSlices.length.sub(1));
}
/**
* @notice Locks the pool (locks both senior and junior tranches and starts the drawdown period). Beyond the drawdown
* period, any unused capital is available to withdraw by all depositors
*/
function lockPool() external override onlyLocker whenNotPaused {
_lockPool();
}
function setFundableAt(uint256 newFundableAt) external override onlyLocker {
fundableAt = newFundableAt;
}
function initializeNextSlice(uint256 _fundableAt) external override onlyLocker whenNotPaused {
require(locked(), "Current slice still active");
require(!creditLine.isLate(), "Creditline is late");
require(creditLine.withinPrincipalGracePeriod(), "Beyond principal grace period");
_initializeNextSlice(_fundableAt);
emit SliceCreated(address(this), poolSlices.length.sub(1));
}
/**
* @notice Triggers an assessment of the creditline and the applies the payments according the tranche waterfall
*/
function assess() external override whenNotPaused {
_assess();
}
/**
* @notice Allows repaying the creditline. Collects the USDC amount from the sender and triggers an assess
* @param amount The amount to repay
*/
function pay(uint256 amount) external override whenNotPaused {
require(amount > 0, "Must pay more than zero");
collectPayment(amount);
_assess();
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
creditLine.updateGoldfinchConfig();
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
/**
* @notice Pauses the pool and sweeps any remaining funds to the treasury reserve.
*/
function emergencyShutdown() public onlyAdmin {
if (!paused()) {
pause();
}
IERC20withDec usdc = config.getUSDC();
address reserveAddress = config.reserveAddress();
// Sweep any funds to community reserve
uint256 poolBalance = usdc.balanceOf(address(this));
if (poolBalance > 0) {
safeERC20Transfer(usdc, reserveAddress, poolBalance);
}
uint256 clBalance = usdc.balanceOf(address(creditLine));
if (clBalance > 0) {
safeERC20TransferFrom(usdc, address(creditLine), reserveAddress, clBalance);
}
emit EmergencyShutdown(address(this));
}
/**
* @notice Pauses all drawdowns (but not deposits/withdraws)
*/
function pauseDrawdowns() public onlyAdmin {
drawdownsPaused = true;
emit DrawdownsPaused(address(this));
}
/**
* @notice Unpause drawdowns
*/
function unpauseDrawdowns() public onlyAdmin {
drawdownsPaused = false;
emit DrawdownsUnpaused(address(this));
}
/**
* @notice Migrates the accounting variables from the current creditline to a brand new one
* @param _borrower The borrower address
* @param _maxLimit The new max limit
* @param _interestApr The new interest APR
* @param _paymentPeriodInDays The new payment period in days
* @param _termInDays The new term in days
* @param _lateFeeApr The new late fee APR
*/
function migrateCreditLine(
address _borrower,
uint256 _maxLimit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) public onlyAdmin {
require(_borrower != address(0), "Borrower must not be empty");
require(_paymentPeriodInDays != 0, "Payment period invalid");
require(_termInDays != 0, "Term must not be empty");
address originalClAddr = address(creditLine);
createAndSetCreditLine(
_borrower,
_maxLimit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays
);
address newClAddr = address(creditLine);
TranchingLogic.migrateAccountingVariables(originalClAddr, newClAddr);
TranchingLogic.closeCreditLine(originalClAddr);
address originalBorrower = IV2CreditLine(originalClAddr).borrower();
address newBorrower = IV2CreditLine(newClAddr).borrower();
// Ensure Roles
if (originalBorrower != newBorrower) {
revokeRole(LOCKER_ROLE, originalBorrower);
grantRole(LOCKER_ROLE, newBorrower);
}
// Transfer any funds to new CL
uint256 clBalance = config.getUSDC().balanceOf(originalClAddr);
if (clBalance > 0) {
safeERC20TransferFrom(config.getUSDC(), originalClAddr, newClAddr, clBalance);
}
emit CreditLineMigrated(originalClAddr, newClAddr);
}
/**
* @notice Migrates to a new creditline without copying the accounting variables
*/
function migrateAndSetNewCreditLine(address newCl) public onlyAdmin {
require(newCl != address(0), "Creditline cannot be empty");
address originalClAddr = address(creditLine);
// Transfer any funds to new CL
uint256 clBalance = config.getUSDC().balanceOf(originalClAddr);
if (clBalance > 0) {
safeERC20TransferFrom(config.getUSDC(), originalClAddr, newCl, clBalance);
}
TranchingLogic.closeCreditLine(originalClAddr);
// set new CL
creditLine = IV2CreditLine(newCl);
// sanity check that the new address is in fact a creditline
creditLine.limit();
emit CreditLineMigrated(originalClAddr, address(creditLine));
}
// CreditLine proxy method
function setLimit(uint256 newAmount) external onlyAdmin {
return creditLine.setLimit(newAmount);
}
function setMaxLimit(uint256 newAmount) external onlyAdmin {
return creditLine.setMaxLimit(newAmount);
}
function getTranche(uint256 tranche) public view override returns (TrancheInfo memory) {
return getTrancheInfo(tranche);
}
function numSlices() public view returns (uint256) {
return poolSlices.length;
}
/**
* @notice Converts USDC amounts to share price
* @param amount The USDC amount to convert
* @param totalShares The total shares outstanding
* @return The share price of the input amount
*/
function usdcToSharePrice(uint256 amount, uint256 totalShares) public pure returns (uint256) {
return TranchingLogic.usdcToSharePrice(amount, totalShares);
}
/**
* @notice Converts share price to USDC amounts
* @param sharePrice The share price to convert
* @param totalShares The total shares outstanding
* @return The USDC amount of the input share price
*/
function sharePriceToUsdc(uint256 sharePrice, uint256 totalShares) public pure returns (uint256) {
return TranchingLogic.sharePriceToUsdc(sharePrice, totalShares);
}
/**
* @notice Returns the total junior capital deposited
* @return The total USDC amount deposited into all junior tranches
*/
function totalJuniorDeposits() external view override returns (uint256) {
uint256 total;
for (uint256 i = 0; i < poolSlices.length; i++) {
total = total.add(poolSlices[i].juniorTranche.principalDeposited);
}
return total;
}
/**
* @notice Determines the amount of interest and principal redeemable by a particular tokenId
* @param tokenId The token representing the position
* @return interestRedeemable The interest available to redeem
* @return principalRedeemable The principal available to redeem
*/
function availableToWithdraw(uint256 tokenId)
public
view
override
returns (uint256 interestRedeemable, uint256 principalRedeemable)
{
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche);
if (currentTime() > trancheInfo.lockedUntil) {
return redeemableInterestAndPrincipal(trancheInfo, tokenInfo);
} else {
return (0, 0);
}
}
/* Internal functions */
function _withdraw(
TrancheInfo storage trancheInfo,
IPoolTokens.TokenInfo memory tokenInfo,
uint256 tokenId,
uint256 amount
) internal returns (uint256 interestWithdrawn, uint256 principalWithdrawn) {
require(config.getPoolTokens().isApprovedOrOwner(msg.sender, tokenId), "Not token owner");
require(config.getGo().goOnlyIdTypes(msg.sender, allowedUIDTypes), "Address not go-listed");
require(amount > 0, "Must withdraw more than zero");
(uint256 interestRedeemable, uint256 principalRedeemable) = redeemableInterestAndPrincipal(trancheInfo, tokenInfo);
uint256 netRedeemable = interestRedeemable.add(principalRedeemable);
require(amount <= netRedeemable, "Invalid redeem amount");
require(currentTime() > trancheInfo.lockedUntil, "Tranche is locked");
// If the tranche has not been locked, ensure the deposited amount is correct
if (trancheInfo.lockedUntil == 0) {
trancheInfo.principalDeposited = trancheInfo.principalDeposited.sub(amount);
}
uint256 interestToRedeem = Math.min(interestRedeemable, amount);
uint256 principalToRedeem = Math.min(principalRedeemable, amount.sub(interestToRedeem));
config.getPoolTokens().redeem(tokenId, principalToRedeem, interestToRedeem);
safeERC20TransferFrom(config.getUSDC(), address(this), msg.sender, principalToRedeem.add(interestToRedeem));
emit WithdrawalMade(msg.sender, tokenInfo.tranche, tokenId, interestToRedeem, principalToRedeem);
return (interestToRedeem, principalToRedeem);
}
function _isSeniorTrancheId(uint256 trancheId) internal pure returns (bool) {
return trancheId.mod(NUM_TRANCHES_PER_SLICE) == 1;
}
function redeemableInterestAndPrincipal(TrancheInfo storage trancheInfo, IPoolTokens.TokenInfo memory tokenInfo)
internal
view
returns (uint256 interestRedeemable, uint256 principalRedeemable)
{
// This supports withdrawing before or after locking because principal share price starts at 1
// and is set to 0 on lock. Interest share price is always 0 until interest payments come back, when it increases
uint256 maxPrincipalRedeemable = sharePriceToUsdc(trancheInfo.principalSharePrice, tokenInfo.principalAmount);
// The principalAmount is used as the totalShares because we want the interestSharePrice to be expressed as a
// percent of total loan value e.g. if the interest is 10% APR, the interestSharePrice should approach a max of 0.1.
uint256 maxInterestRedeemable = sharePriceToUsdc(trancheInfo.interestSharePrice, tokenInfo.principalAmount);
interestRedeemable = maxInterestRedeemable.sub(tokenInfo.interestRedeemed);
principalRedeemable = maxPrincipalRedeemable.sub(tokenInfo.principalRedeemed);
return (interestRedeemable, principalRedeemable);
}
function _lockJuniorCapital(uint256 sliceId) internal {
require(!locked(), "Pool already locked");
require(poolSlices[sliceId].juniorTranche.lockedUntil == 0, "Junior tranche already locked");
uint256 lockedUntil = currentTime().add(config.getDrawdownPeriodInSeconds());
poolSlices[sliceId].juniorTranche.lockedUntil = lockedUntil;
emit TrancheLocked(address(this), poolSlices[sliceId].juniorTranche.id, lockedUntil);
}
function _lockPool() internal {
uint256 sliceId = poolSlices.length.sub(1);
require(poolSlices[sliceId].juniorTranche.lockedUntil > 0, "Junior tranche must be locked");
// Allow locking the pool only once; do not allow extending the lock of an
// already-locked pool. Otherwise the locker could keep the pool locked
// indefinitely, preventing withdrawals.
require(poolSlices[sliceId].seniorTranche.lockedUntil == 0, "Lock cannot be extended");
uint256 currentTotal = poolSlices[sliceId].juniorTranche.principalDeposited.add(
poolSlices[sliceId].seniorTranche.principalDeposited
);
creditLine.setLimit(Math.min(creditLine.limit().add(currentTotal), creditLine.maxLimit()));
// We start the drawdown period, so backers can withdraw unused capital after borrower draws down
uint256 lockPeriod = config.getDrawdownPeriodInSeconds();
poolSlices[sliceId].seniorTranche.lockedUntil = currentTime().add(lockPeriod);
poolSlices[sliceId].juniorTranche.lockedUntil = currentTime().add(lockPeriod);
emit TrancheLocked(
address(this),
poolSlices[sliceId].seniorTranche.id,
poolSlices[sliceId].seniorTranche.lockedUntil
);
emit TrancheLocked(
address(this),
poolSlices[sliceId].juniorTranche.id,
poolSlices[sliceId].juniorTranche.lockedUntil
);
}
function _initializeNextSlice(uint256 newFundableAt) internal {
uint256 numSlices = poolSlices.length;
require(numSlices < 5, "Cannot exceed 5 slices");
poolSlices.push(
PoolSlice({
seniorTranche: TrancheInfo({
id: numSlices.mul(NUM_TRANCHES_PER_SLICE).add(1),
principalSharePrice: usdcToSharePrice(1, 1),
interestSharePrice: 0,
principalDeposited: 0,
lockedUntil: 0
}),
juniorTranche: TrancheInfo({
id: numSlices.mul(NUM_TRANCHES_PER_SLICE).add(2),
principalSharePrice: usdcToSharePrice(1, 1),
interestSharePrice: 0,
principalDeposited: 0,
lockedUntil: 0
}),
totalInterestAccrued: 0,
principalDeployed: 0
})
);
fundableAt = newFundableAt;
}
function collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) internal returns (uint256 totalReserveAmount) {
safeERC20TransferFrom(config.getUSDC(), from, address(this), principal.add(interest), "Failed to collect payment");
uint256 reserveFeePercent = ONE_HUNDRED.div(config.getReserveDenominator()); // Convert the denonminator to percent
ApplyResult memory result = TranchingLogic.applyToAllSeniorTranches(
poolSlices,
interest,
principal,
reserveFeePercent,
totalDeployed,
creditLine,
juniorFeePercent
);
totalReserveAmount = result.reserveDeduction.add(
TranchingLogic.applyToAllJuniorTranches(
poolSlices,
result.interestRemaining,
result.principalRemaining,
reserveFeePercent,
totalDeployed,
creditLine
)
);
sendToReserve(totalReserveAmount);
return totalReserveAmount;
}
// If the senior tranche of the current slice is locked, then the pool is not open to any more deposits
// (could throw off leverage ratio)
function locked() internal view returns (bool) {
return poolSlices[poolSlices.length.sub(1)].seniorTranche.lockedUntil > 0;
}
function createAndSetCreditLine(
address _borrower,
uint256 _maxLimit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) internal {
address _creditLine = config.getGoldfinchFactory().createCreditLine();
creditLine = IV2CreditLine(_creditLine);
creditLine.initialize(
address(config),
address(this), // Set self as the owner
_borrower,
_maxLimit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays
);
}
function getTrancheInfo(uint256 trancheId) internal view returns (TrancheInfo storage) {
require(trancheId > 0 && trancheId <= poolSlices.length.mul(NUM_TRANCHES_PER_SLICE), "Unsupported tranche");
uint256 sliceId = ((trancheId.add(trancheId.mod(NUM_TRANCHES_PER_SLICE))).div(NUM_TRANCHES_PER_SLICE)).sub(1);
PoolSlice storage slice = poolSlices[sliceId];
TrancheInfo storage trancheInfo = trancheId.mod(NUM_TRANCHES_PER_SLICE) == 1
? slice.seniorTranche
: slice.juniorTranche;
return trancheInfo;
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function sendToReserve(uint256 amount) internal {
emit ReserveFundsCollected(address(this), amount);
safeERC20TransferFrom(
config.getUSDC(),
address(this),
config.reserveAddress(),
amount,
"Failed to send to reserve"
);
}
function collectPayment(uint256 amount) internal {
safeERC20TransferFrom(config.getUSDC(), msg.sender, address(creditLine), amount, "Failed to collect payment");
}
function _assess() internal {
// We need to make sure the pool is locked before we allocate rewards to ensure it's not
// possible to game rewards by sandwiching an interest payment to an unlocked pool
// It also causes issues trying to allocate payments to an empty slice (divide by zero)
require(locked(), "Pool is not locked");
uint256 interestAccrued = creditLine.totalInterestAccrued();
(uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = creditLine.assess();
interestAccrued = creditLine.totalInterestAccrued().sub(interestAccrued);
// Split the interest accrued proportionally across slices so we know how much interest goes to each slice
// We need this because the slice start at different times, so we cannot retroactively allocate the interest
// linearly
uint256[] memory principalPaymentsPerSlice = new uint256[](poolSlices.length);
for (uint256 i = 0; i < poolSlices.length; i++) {
uint256 interestForSlice = TranchingLogic.scaleByFraction(
interestAccrued,
poolSlices[i].principalDeployed,
totalDeployed
);
principalPaymentsPerSlice[i] = TranchingLogic.scaleByFraction(
principalPayment,
poolSlices[i].principalDeployed,
totalDeployed
);
poolSlices[i].totalInterestAccrued = poolSlices[i].totalInterestAccrued.add(interestForSlice);
}
if (interestPayment > 0 || principalPayment > 0) {
uint256 reserveAmount = collectInterestAndPrincipal(
address(creditLine),
interestPayment,
principalPayment.add(paymentRemaining)
);
for (uint256 i = 0; i < poolSlices.length; i++) {
poolSlices[i].principalDeployed = poolSlices[i].principalDeployed.sub(principalPaymentsPerSlice[i]);
totalDeployed = totalDeployed.sub(principalPaymentsPerSlice[i]);
}
config.getBackerRewards().allocateRewards(interestPayment);
emit PaymentApplied(
creditLine.borrower(),
address(this),
interestPayment,
principalPayment,
paymentRemaining,
reserveAmount
);
}
emit TranchedPoolAssessed(address(this));
}
modifier onlyLocker() {
require(hasRole(LOCKER_ROLE, msg.sender), "Must have locker role");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
/**
* @title Safe ERC20 Transfer
* @notice Reverts when transfer is not successful
* @author Goldfinch
*/
abstract contract SafeERC20Transfer {
function safeERC20Transfer(
IERC20 erc20,
address to,
uint256 amount,
string memory message
) internal {
require(to != address(0), "Can't send to zero address");
bool success = erc20.transfer(to, amount);
require(success, message);
}
function safeERC20Transfer(
IERC20 erc20,
address to,
uint256 amount
) internal {
safeERC20Transfer(erc20, to, amount, "Failed to transfer ERC20");
}
function safeERC20TransferFrom(
IERC20 erc20,
address from,
address to,
uint256 amount,
string memory message
) internal {
require(to != address(0), "Can't send to zero address");
bool success = erc20.transferFrom(from, to, amount);
require(success, message);
}
function safeERC20TransferFrom(
IERC20 erc20,
address from,
address to,
uint256 amount
) internal {
string memory message = "Failed to transfer ERC20";
safeERC20TransferFrom(erc20, from, to, amount, message);
}
function safeERC20Approve(
IERC20 erc20,
address spender,
uint256 allowance,
string memory message
) internal {
bool success = erc20.approve(spender, allowance);
require(success, message);
}
function safeERC20Approve(
IERC20 erc20,
address spender,
uint256 allowance
) internal {
string memory message = "Failed to approve ERC20";
safeERC20Approve(erc20, spender, allowance, message);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../interfaces/IV2CreditLine.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../external/FixedPoint.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title TranchingLogic
* @notice Library for handling the payments waterfall
* @author Goldfinch
*/
library TranchingLogic {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
event SharePriceUpdated(
address indexed pool,
uint256 indexed tranche,
uint256 principalSharePrice,
int256 principalDelta,
uint256 interestSharePrice,
int256 interestDelta
);
uint256 public constant FP_SCALING_FACTOR = 1e18;
uint256 public constant ONE_HUNDRED = 100; // Need this because we cannot call .div on a literal 100
function usdcToSharePrice(uint256 amount, uint256 totalShares) public pure returns (uint256) {
return totalShares == 0 ? 0 : amount.mul(FP_SCALING_FACTOR).div(totalShares);
}
function sharePriceToUsdc(uint256 sharePrice, uint256 totalShares) public pure returns (uint256) {
return sharePrice.mul(totalShares).div(FP_SCALING_FACTOR);
}
function redeemableInterestAndPrincipal(
ITranchedPool.TrancheInfo storage trancheInfo,
IPoolTokens.TokenInfo memory tokenInfo
) public view returns (uint256 interestRedeemable, uint256 principalRedeemable) {
// This supports withdrawing before or after locking because principal share price starts at 1
// and is set to 0 on lock. Interest share price is always 0 until interest payments come back, when it increases
uint256 maxPrincipalRedeemable = sharePriceToUsdc(trancheInfo.principalSharePrice, tokenInfo.principalAmount);
// The principalAmount is used as the totalShares because we want the interestSharePrice to be expressed as a
// percent of total loan value e.g. if the interest is 10% APR, the interestSharePrice should approach a max of 0.1.
uint256 maxInterestRedeemable = sharePriceToUsdc(trancheInfo.interestSharePrice, tokenInfo.principalAmount);
interestRedeemable = maxInterestRedeemable.sub(tokenInfo.interestRedeemed);
principalRedeemable = maxPrincipalRedeemable.sub(tokenInfo.principalRedeemed);
return (interestRedeemable, principalRedeemable);
}
function calculateExpectedSharePrice(
ITranchedPool.TrancheInfo memory tranche,
uint256 amount,
ITranchedPool.PoolSlice memory slice
) public pure returns (uint256) {
uint256 sharePrice = usdcToSharePrice(amount, tranche.principalDeposited);
return scaleByPercentOwnership(tranche, sharePrice, slice);
}
function scaleForSlice(
ITranchedPool.PoolSlice memory slice,
uint256 amount,
uint256 totalDeployed
) public pure returns (uint256) {
return scaleByFraction(amount, slice.principalDeployed, totalDeployed);
}
// We need to create this struct so we don't run into a stack too deep error due to too many variables
function getSliceInfo(
ITranchedPool.PoolSlice memory slice,
IV2CreditLine creditLine,
uint256 totalDeployed,
uint256 reserveFeePercent
) public view returns (ITranchedPool.SliceInfo memory) {
(uint256 interestAccrued, uint256 principalAccrued) = getTotalInterestAndPrincipal(
slice,
creditLine,
totalDeployed
);
return
ITranchedPool.SliceInfo({
reserveFeePercent: reserveFeePercent,
interestAccrued: interestAccrued,
principalAccrued: principalAccrued
});
}
function getTotalInterestAndPrincipal(
ITranchedPool.PoolSlice memory slice,
IV2CreditLine creditLine,
uint256 totalDeployed
) public view returns (uint256 interestAccrued, uint256 principalAccrued) {
principalAccrued = creditLine.principalOwed();
// In addition to principal actually owed, we need to account for early principal payments
// If the borrower pays back 5K early on a 10K loan, the actual principal accrued should be
// 5K (balance- deployed) + 0 (principal owed)
principalAccrued = totalDeployed.sub(creditLine.balance()).add(principalAccrued);
// Now we need to scale that correctly for the slice we're interested in
principalAccrued = scaleForSlice(slice, principalAccrued, totalDeployed);
// Finally, we need to account for partial drawdowns. e.g. If 20K was deposited, and only 10K was drawn down,
// Then principal accrued should start at 10K (total deposited - principal deployed), not 0. This is because
// share price starts at 1, and is decremented by what was drawn down.
uint256 totalDeposited = slice.seniorTranche.principalDeposited.add(slice.juniorTranche.principalDeposited);
principalAccrued = totalDeposited.sub(slice.principalDeployed).add(principalAccrued);
return (slice.totalInterestAccrued, principalAccrued);
}
function scaleByFraction(
uint256 amount,
uint256 fraction,
uint256 total
) public pure returns (uint256) {
FixedPoint.Unsigned memory totalAsFixedPoint = FixedPoint.fromUnscaledUint(total);
FixedPoint.Unsigned memory fractionAsFixedPoint = FixedPoint.fromUnscaledUint(fraction);
return fractionAsFixedPoint.div(totalAsFixedPoint).mul(amount).div(FP_SCALING_FACTOR).rawValue;
}
function applyToAllSeniorTranches(
ITranchedPool.PoolSlice[] storage poolSlices,
uint256 interest,
uint256 principal,
uint256 reserveFeePercent,
uint256 totalDeployed,
IV2CreditLine creditLine,
uint256 juniorFeePercent
) public returns (ITranchedPool.ApplyResult memory) {
ITranchedPool.ApplyResult memory seniorApplyResult;
for (uint256 i = 0; i < poolSlices.length; i++) {
ITranchedPool.SliceInfo memory sliceInfo = getSliceInfo(
poolSlices[i],
creditLine,
totalDeployed,
reserveFeePercent
);
// Since slices cannot be created when the loan is late, all interest collected can be assumed to split
// pro-rata across the slices. So we scale the interest and principal to the slice
ITranchedPool.ApplyResult memory applyResult = applyToSeniorTranche(
poolSlices[i],
scaleForSlice(poolSlices[i], interest, totalDeployed),
scaleForSlice(poolSlices[i], principal, totalDeployed),
juniorFeePercent,
sliceInfo
);
emitSharePriceUpdatedEvent(poolSlices[i].seniorTranche, applyResult);
seniorApplyResult.interestRemaining = seniorApplyResult.interestRemaining.add(applyResult.interestRemaining);
seniorApplyResult.principalRemaining = seniorApplyResult.principalRemaining.add(applyResult.principalRemaining);
seniorApplyResult.reserveDeduction = seniorApplyResult.reserveDeduction.add(applyResult.reserveDeduction);
}
return seniorApplyResult;
}
function applyToAllJuniorTranches(
ITranchedPool.PoolSlice[] storage poolSlices,
uint256 interest,
uint256 principal,
uint256 reserveFeePercent,
uint256 totalDeployed,
IV2CreditLine creditLine
) public returns (uint256 totalReserveAmount) {
for (uint256 i = 0; i < poolSlices.length; i++) {
ITranchedPool.SliceInfo memory sliceInfo = getSliceInfo(
poolSlices[i],
creditLine,
totalDeployed,
reserveFeePercent
);
// Any remaining interest and principal is then shared pro-rata with the junior slices
ITranchedPool.ApplyResult memory applyResult = applyToJuniorTranche(
poolSlices[i],
scaleForSlice(poolSlices[i], interest, totalDeployed),
scaleForSlice(poolSlices[i], principal, totalDeployed),
sliceInfo
);
emitSharePriceUpdatedEvent(poolSlices[i].juniorTranche, applyResult);
totalReserveAmount = totalReserveAmount.add(applyResult.reserveDeduction);
}
return totalReserveAmount;
}
function emitSharePriceUpdatedEvent(
ITranchedPool.TrancheInfo memory tranche,
ITranchedPool.ApplyResult memory applyResult
) internal {
emit SharePriceUpdated(
address(this),
tranche.id,
tranche.principalSharePrice,
int256(tranche.principalSharePrice.sub(applyResult.oldPrincipalSharePrice)),
tranche.interestSharePrice,
int256(tranche.interestSharePrice.sub(applyResult.oldInterestSharePrice))
);
}
function applyToSeniorTranche(
ITranchedPool.PoolSlice storage slice,
uint256 interestRemaining,
uint256 principalRemaining,
uint256 juniorFeePercent,
ITranchedPool.SliceInfo memory sliceInfo
) public returns (ITranchedPool.ApplyResult memory) {
// First determine the expected share price for the senior tranche. This is the gross amount the senior
// tranche should receive.
uint256 expectedInterestSharePrice = calculateExpectedSharePrice(
slice.seniorTranche,
sliceInfo.interestAccrued,
slice
);
uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice(
slice.seniorTranche,
sliceInfo.principalAccrued,
slice
);
// Deduct the junior fee and the protocol reserve
uint256 desiredNetInterestSharePrice = scaleByFraction(
expectedInterestSharePrice,
ONE_HUNDRED.sub(juniorFeePercent.add(sliceInfo.reserveFeePercent)),
ONE_HUNDRED
);
// Collect protocol fee interest received (we've subtracted this from the senior portion above)
uint256 reserveDeduction = scaleByFraction(interestRemaining, sliceInfo.reserveFeePercent, ONE_HUNDRED);
interestRemaining = interestRemaining.sub(reserveDeduction);
uint256 oldInterestSharePrice = slice.seniorTranche.interestSharePrice;
uint256 oldPrincipalSharePrice = slice.seniorTranche.principalSharePrice;
// Apply the interest remaining so we get up to the netInterestSharePrice
(interestRemaining, principalRemaining) = applyBySharePrice(
slice.seniorTranche,
interestRemaining,
principalRemaining,
desiredNetInterestSharePrice,
expectedPrincipalSharePrice
);
return
ITranchedPool.ApplyResult({
interestRemaining: interestRemaining,
principalRemaining: principalRemaining,
reserveDeduction: reserveDeduction,
oldInterestSharePrice: oldInterestSharePrice,
oldPrincipalSharePrice: oldPrincipalSharePrice
});
}
function applyToJuniorTranche(
ITranchedPool.PoolSlice storage slice,
uint256 interestRemaining,
uint256 principalRemaining,
ITranchedPool.SliceInfo memory sliceInfo
) public returns (ITranchedPool.ApplyResult memory) {
// Then fill up the junior tranche with all the interest remaining, upto the principal share price
uint256 expectedInterestSharePrice = slice.juniorTranche.interestSharePrice.add(
usdcToSharePrice(interestRemaining, slice.juniorTranche.principalDeposited)
);
uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice(
slice.juniorTranche,
sliceInfo.principalAccrued,
slice
);
uint256 oldInterestSharePrice = slice.juniorTranche.interestSharePrice;
uint256 oldPrincipalSharePrice = slice.juniorTranche.principalSharePrice;
(interestRemaining, principalRemaining) = applyBySharePrice(
slice.juniorTranche,
interestRemaining,
principalRemaining,
expectedInterestSharePrice,
expectedPrincipalSharePrice
);
// All remaining interest and principal is applied towards the junior tranche as interest
interestRemaining = interestRemaining.add(principalRemaining);
// Since any principal remaining is treated as interest (there is "extra" interest to be distributed)
// we need to make sure to collect the protocol fee on the additional interest (we only deducted the
// fee on the original interest portion)
uint256 reserveDeduction = scaleByFraction(principalRemaining, sliceInfo.reserveFeePercent, ONE_HUNDRED);
interestRemaining = interestRemaining.sub(reserveDeduction);
principalRemaining = 0;
(interestRemaining, principalRemaining) = applyByAmount(
slice.juniorTranche,
interestRemaining.add(principalRemaining),
0,
interestRemaining.add(principalRemaining),
0
);
return
ITranchedPool.ApplyResult({
interestRemaining: interestRemaining,
principalRemaining: principalRemaining,
reserveDeduction: reserveDeduction,
oldInterestSharePrice: oldInterestSharePrice,
oldPrincipalSharePrice: oldPrincipalSharePrice
});
}
function applyBySharePrice(
ITranchedPool.TrancheInfo storage tranche,
uint256 interestRemaining,
uint256 principalRemaining,
uint256 desiredInterestSharePrice,
uint256 desiredPrincipalSharePrice
) public returns (uint256, uint256) {
uint256 desiredInterestAmount = desiredAmountFromSharePrice(
desiredInterestSharePrice,
tranche.interestSharePrice,
tranche.principalDeposited
);
uint256 desiredPrincipalAmount = desiredAmountFromSharePrice(
desiredPrincipalSharePrice,
tranche.principalSharePrice,
tranche.principalDeposited
);
return applyByAmount(tranche, interestRemaining, principalRemaining, desiredInterestAmount, desiredPrincipalAmount);
}
function applyByAmount(
ITranchedPool.TrancheInfo storage tranche,
uint256 interestRemaining,
uint256 principalRemaining,
uint256 desiredInterestAmount,
uint256 desiredPrincipalAmount
) public returns (uint256, uint256) {
uint256 totalShares = tranche.principalDeposited;
uint256 newSharePrice;
(interestRemaining, newSharePrice) = applyToSharePrice(
interestRemaining,
tranche.interestSharePrice,
desiredInterestAmount,
totalShares
);
tranche.interestSharePrice = newSharePrice;
(principalRemaining, newSharePrice) = applyToSharePrice(
principalRemaining,
tranche.principalSharePrice,
desiredPrincipalAmount,
totalShares
);
tranche.principalSharePrice = newSharePrice;
return (interestRemaining, principalRemaining);
}
function migrateAccountingVariables(address originalClAddr, address newClAddr) public {
IV2CreditLine originalCl = IV2CreditLine(originalClAddr);
IV2CreditLine newCl = IV2CreditLine(newClAddr);
// Copy over all accounting variables
newCl.setBalance(originalCl.balance());
newCl.setLimit(originalCl.limit());
newCl.setInterestOwed(originalCl.interestOwed());
newCl.setPrincipalOwed(originalCl.principalOwed());
newCl.setTermEndTime(originalCl.termEndTime());
newCl.setNextDueTime(originalCl.nextDueTime());
newCl.setInterestAccruedAsOf(originalCl.interestAccruedAsOf());
newCl.setLastFullPaymentTime(originalCl.lastFullPaymentTime());
newCl.setTotalInterestAccrued(originalCl.totalInterestAccrued());
}
function closeCreditLine(address originalCl) public {
// Close out old CL
IV2CreditLine oldCreditLine = IV2CreditLine(originalCl);
oldCreditLine.setBalance(0);
oldCreditLine.setLimit(0);
oldCreditLine.setMaxLimit(0);
}
function desiredAmountFromSharePrice(
uint256 desiredSharePrice,
uint256 actualSharePrice,
uint256 totalShares
) public pure returns (uint256) {
// If the desired share price is lower, then ignore it, and leave it unchanged
if (desiredSharePrice < actualSharePrice) {
desiredSharePrice = actualSharePrice;
}
uint256 sharePriceDifference = desiredSharePrice.sub(actualSharePrice);
return sharePriceToUsdc(sharePriceDifference, totalShares);
}
function applyToSharePrice(
uint256 amountRemaining,
uint256 currentSharePrice,
uint256 desiredAmount,
uint256 totalShares
) public pure returns (uint256, uint256) {
// If no money left to apply, or don't need any changes, return the original amounts
if (amountRemaining == 0 || desiredAmount == 0) {
return (amountRemaining, currentSharePrice);
}
if (amountRemaining < desiredAmount) {
// We don't have enough money to adjust share price to the desired level. So just use whatever amount is left
desiredAmount = amountRemaining;
}
uint256 sharePriceDifference = usdcToSharePrice(desiredAmount, totalShares);
return (amountRemaining.sub(desiredAmount), currentSharePrice.add(sharePriceDifference));
}
function scaleByPercentOwnership(
ITranchedPool.TrancheInfo memory tranche,
uint256 amount,
ITranchedPool.PoolSlice memory slice
) public pure returns (uint256) {
uint256 totalDeposited = slice.juniorTranche.principalDeposited.add(slice.seniorTranche.principalDeposited);
return scaleByFraction(amount, tranche.principalDeposited, totalDeposited);
}
}
// SPDX-License-Identifier: GPL-3.0-only
// solhint-disable-next-line max-line-length
// Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/MerkleDistributor.sol.
pragma solidity 0.6.12;
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IERC20withDec.sol";
import "../interfaces/IMerkleDirectDistributor.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
contract MerkleDirectDistributor is IMerkleDirectDistributor, BaseUpgradeablePausable {
using SafeERC20 for IERC20withDec;
address public override gfi;
bytes32 public override merkleRoot;
// @dev This is a packed array of booleans.
mapping(uint256 => uint256) private acceptedBitMap;
function initialize(
address owner,
address _gfi,
bytes32 _merkleRoot
) public initializer {
require(owner != address(0), "Owner address cannot be empty");
require(_gfi != address(0), "GFI address cannot be empty");
require(_merkleRoot != 0, "Invalid Merkle root");
__BaseUpgradeablePausable__init(owner);
gfi = _gfi;
merkleRoot = _merkleRoot;
}
function isGrantAccepted(uint256 index) public view override returns (bool) {
uint256 acceptedWordIndex = index / 256;
uint256 acceptedBitIndex = index % 256;
uint256 acceptedWord = acceptedBitMap[acceptedWordIndex];
uint256 mask = (1 << acceptedBitIndex);
return acceptedWord & mask == mask;
}
function _setGrantAccepted(uint256 index) private {
uint256 acceptedWordIndex = index / 256;
uint256 acceptedBitIndex = index % 256;
acceptedBitMap[acceptedWordIndex] = acceptedBitMap[acceptedWordIndex] | (1 << acceptedBitIndex);
}
function acceptGrant(
uint256 index,
uint256 amount,
bytes32[] calldata merkleProof
) external override whenNotPaused {
require(!isGrantAccepted(index), "Grant already accepted");
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(index, msg.sender, amount));
require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof");
// Mark it accepted and perform the granting.
_setGrantAccepted(index);
IERC20withDec(gfi).safeTransfer(msg.sender, amount);
emit GrantAccepted(index, msg.sender, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: GPL-3.0-only
// solhint-disable-next-line max-line-length
// Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/interfaces/IMerkleDistributor.sol.
pragma solidity 0.6.12;
/// @notice Enables the transfer of GFI rewards (referred to as a "grant"), if the grant details exist in this
/// contract's Merkle root.
interface IMerkleDirectDistributor {
/// @notice Returns the address of the GFI contract that is the token distributed as rewards by
/// this contract.
function gfi() external view returns (address);
/// @notice Returns the merkle root of the merkle tree containing grant details available to accept.
function merkleRoot() external view returns (bytes32);
/// @notice Returns true if the index has been marked accepted.
function isGrantAccepted(uint256 index) external view returns (bool);
/// @notice Causes the sender to accept the grant consisting of the given details. Reverts if
/// the inputs (which includes who the sender is) are invalid.
function acceptGrant(
uint256 index,
uint256 amount,
bytes32[] calldata merkleProof
) external;
/// @notice This event is triggered whenever a call to #acceptGrant succeeds.
event GrantAccepted(uint256 indexed index, address indexed account, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/Pool.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../protocol/core/CreditLine.sol";
contract TestCreditLine is CreditLine {}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/Accountant.sol";
import "../protocol/core/CreditLine.sol";
contract TestAccountant {
function calculateInterestAndPrincipalAccrued(
address creditLineAddress,
uint256 timestamp,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
CreditLine cl = CreditLine(creditLineAddress);
return Accountant.calculateInterestAndPrincipalAccrued(cl, timestamp, lateFeeGracePeriod);
}
function calculateWritedownFor(
address creditLineAddress,
uint256 blockNumber,
uint256 gracePeriod,
uint256 maxLatePeriods
) public view returns (uint256, uint256) {
CreditLine cl = CreditLine(creditLineAddress);
return Accountant.calculateWritedownFor(cl, blockNumber, gracePeriod, maxLatePeriods);
}
function calculateAmountOwedForOneDay(address creditLineAddress) public view returns (FixedPoint.Unsigned memory) {
CreditLine cl = CreditLine(creditLineAddress);
return Accountant.calculateAmountOwedForOneDay(cl);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/IPoolTokens.sol";
import "./Accountant.sol";
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
/**
* @title Goldfinch's SeniorPool contract
* @notice Main entry point for senior LPs (a.k.a. capital providers)
* Automatically invests across borrower pools using an adjustable strategy.
* @author Goldfinch
*/
contract SeniorPool is BaseUpgradeablePausable, ISeniorPool {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
using SafeMath for uint256;
uint256 public compoundBalance;
mapping(ITranchedPool => uint256) public writedowns;
event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares);
event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount);
event InterestCollected(address indexed payer, uint256 amount);
event PrincipalCollected(address indexed payer, uint256 amount);
event ReserveFundsCollected(address indexed user, uint256 amount);
event PrincipalWrittenDown(address indexed tranchedPool, int256 amount);
event InvestmentMadeInSenior(address indexed tranchedPool, uint256 amount);
event InvestmentMadeInJunior(address indexed tranchedPool, uint256 amount);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
// Initialize sharePrice to be identical to the legacy pool. This is in the initializer
// because it must only ever happen once.
sharePrice = config.getPool().sharePrice();
totalLoansOutstanding = config.getCreditDesk().totalLoansOutstanding();
totalWritedowns = config.getCreditDesk().totalWritedowns();
IERC20withDec usdc = config.getUSDC();
// Sanity check the address
usdc.totalSupply();
bool success = usdc.approve(address(this), uint256(-1));
require(success, "Failed to approve USDC");
}
/**
* @notice Deposits `amount` USDC from msg.sender into the SeniorPool, and grants you the
* equivalent value of FIDU tokens
* @param amount The amount of USDC to deposit
*/
function deposit(uint256 amount) public override whenNotPaused nonReentrant returns (uint256 depositShares) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
require(amount > 0, "Must deposit more than zero");
// Check if the amount of new shares to be added is within limits
depositShares = getNumShares(amount);
uint256 potentialNewTotalShares = totalShares().add(depositShares);
require(sharesWithinLimit(potentialNewTotalShares), "Deposit would put the senior pool over the total limit.");
emit DepositMade(msg.sender, amount, depositShares);
bool success = doUSDCTransfer(msg.sender, address(this), amount);
require(success, "Failed to transfer for deposit");
config.getFidu().mintTo(msg.sender, depositShares);
return depositShares;
}
/**
* @notice Identical to deposit, except it allows for a passed up signature to permit
* the Senior Pool to move funds on behalf of the user, all within one transaction.
* @param amount The amount of USDC to deposit
* @param v secp256k1 signature component
* @param r secp256k1 signature component
* @param s secp256k1 signature component
*/
function depositWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public override returns (uint256 depositShares) {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
return deposit(amount);
}
/**
* @notice Withdraws USDC from the SeniorPool to msg.sender, and burns the equivalent value of FIDU tokens
* @param usdcAmount The amount of USDC to withdraw
*/
function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant returns (uint256 amount) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
require(usdcAmount > 0, "Must withdraw more than zero");
// This MUST happen before calculating withdrawShares, otherwise the share price
// changes between calculation and burning of Fidu, which creates a asset/liability mismatch
if (compoundBalance > 0) {
_sweepFromCompound();
}
uint256 withdrawShares = getNumShares(usdcAmount);
return _withdraw(usdcAmount, withdrawShares);
}
/**
* @notice Withdraws USDC (denominated in FIDU terms) from the SeniorPool to msg.sender
* @param fiduAmount The amount of USDC to withdraw in terms of FIDU shares
*/
function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant returns (uint256 amount) {
require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed");
require(fiduAmount > 0, "Must withdraw more than zero");
// This MUST happen before calculating withdrawShares, otherwise the share price
// changes between calculation and burning of Fidu, which creates a asset/liability mismatch
if (compoundBalance > 0) {
_sweepFromCompound();
}
uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount);
uint256 withdrawShares = fiduAmount;
return _withdraw(usdcAmount, withdrawShares);
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
/**
* @notice Moves any USDC still in the SeniorPool to Compound, and tracks the amount internally.
* This is done to earn interest on latent funds until we have other borrowers who can use it.
*
* Requirements:
* - The caller must be an admin.
*/
function sweepToCompound() public override onlyAdmin whenNotPaused {
IERC20 usdc = config.getUSDC();
uint256 usdcBalance = usdc.balanceOf(address(this));
ICUSDCContract cUSDC = config.getCUSDCContract();
// Approve compound to the exact amount
bool success = usdc.approve(address(cUSDC), usdcBalance);
require(success, "Failed to approve USDC for compound");
sweepToCompound(cUSDC, usdcBalance);
// Remove compound approval to be extra safe
success = config.getUSDC().approve(address(cUSDC), 0);
require(success, "Failed to approve USDC for compound");
}
/**
* @notice Moves any USDC from Compound back to the SeniorPool, and recognizes interest earned.
* This is done automatically on drawdown or withdraw, but can be called manually if necessary.
*
* Requirements:
* - The caller must be an admin.
*/
function sweepFromCompound() public override onlyAdmin whenNotPaused {
_sweepFromCompound();
}
/**
* @notice Invest in an ITranchedPool's senior tranche using the senior pool's strategy
* @param pool An ITranchedPool whose senior tranche should be considered for investment
*/
function invest(ITranchedPool pool) public override whenNotPaused nonReentrant {
require(validPool(pool), "Pool must be valid");
if (compoundBalance > 0) {
_sweepFromCompound();
}
ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy();
uint256 amount = strategy.invest(this, pool);
require(amount > 0, "Investment amount must be positive");
approvePool(pool, amount);
pool.deposit(uint256(ITranchedPool.Tranches.Senior), amount);
emit InvestmentMadeInSenior(address(pool), amount);
totalLoansOutstanding = totalLoansOutstanding.add(amount);
}
function estimateInvestment(ITranchedPool pool) public view override returns (uint256) {
require(validPool(pool), "Pool must be valid");
ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy();
return strategy.estimateInvestment(this, pool);
}
/**
* @notice Redeem interest and/or principal from an ITranchedPool investment
* @param tokenId the ID of an IPoolTokens token to be redeemed
*/
function redeem(uint256 tokenId) public override whenNotPaused nonReentrant {
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
(uint256 interestRedeemed, uint256 principalRedeemed) = pool.withdrawMax(tokenId);
_collectInterestAndPrincipal(address(pool), interestRedeemed, principalRedeemed);
}
/**
* @notice Write down an ITranchedPool investment. This will adjust the senior pool's share price
* down if we're considering the investment a loss, or up if the borrower has subsequently
* made repayments that restore confidence that the full loan will be repaid.
* @param tokenId the ID of an IPoolTokens token to be considered for writedown
*/
function writedown(uint256 tokenId) public override whenNotPaused nonReentrant {
IPoolTokens poolTokens = config.getPoolTokens();
require(address(this) == poolTokens.ownerOf(tokenId), "Only tokens owned by the senior pool can be written down");
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
require(validPool(pool), "Pool must be valid");
uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed);
(uint256 writedownPercent, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining);
uint256 prevWritedownAmount = writedowns[pool];
if (writedownPercent == 0 && prevWritedownAmount == 0) {
return;
}
int256 writedownDelta = int256(prevWritedownAmount) - int256(writedownAmount);
writedowns[pool] = writedownAmount;
distributeLosses(writedownDelta);
if (writedownDelta > 0) {
// If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns.
totalWritedowns = totalWritedowns.sub(uint256(writedownDelta));
} else {
totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1));
}
emit PrincipalWrittenDown(address(pool), writedownDelta);
}
/**
* @notice Calculates the writedown amount for a particular pool position
* @param tokenId The token reprsenting the position
* @return The amount in dollars the principal should be written down by
*/
function calculateWritedown(uint256 tokenId) public view override returns (uint256) {
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed);
(, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining);
return writedownAmount;
}
/**
* @notice Returns the net assests controlled by and owed to the pool
*/
function assets() public view override returns (uint256) {
return
compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(totalLoansOutstanding).sub(totalWritedowns);
}
/**
* @notice Converts and USDC amount to FIDU amount
* @param amount USDC amount to convert to FIDU
*/
function getNumShares(uint256 amount) public view override returns (uint256) {
return usdcToFidu(amount).mul(fiduMantissa()).div(sharePrice);
}
/* Internal Functions */
function _calculateWritedown(ITranchedPool pool, uint256 principal)
internal
view
returns (uint256 writedownPercent, uint256 writedownAmount)
{
return
Accountant.calculateWritedownForPrincipal(
pool.creditLine(),
principal,
currentTime(),
config.getLatenessGracePeriodInDays(),
config.getLatenessMaxDays()
);
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function distributeLosses(int256 writedownDelta) internal {
if (writedownDelta > 0) {
uint256 delta = usdcToSharePrice(uint256(writedownDelta));
sharePrice = sharePrice.add(delta);
} else {
// If delta is negative, convert to positive uint, and sub from sharePrice
uint256 delta = usdcToSharePrice(uint256(writedownDelta * -1));
sharePrice = sharePrice.sub(delta);
}
}
function fiduMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(18);
}
function usdcMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(6);
}
function usdcToFidu(uint256 amount) internal pure returns (uint256) {
return amount.mul(fiduMantissa()).div(usdcMantissa());
}
function fiduToUSDC(uint256 amount) internal pure returns (uint256) {
return amount.div(fiduMantissa().div(usdcMantissa()));
}
function getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) {
return fiduToUSDC(fiduAmount.mul(sharePrice).div(fiduMantissa()));
}
function sharesWithinLimit(uint256 _totalShares) internal view returns (bool) {
return
_totalShares.mul(sharePrice).div(fiduMantissa()) <=
usdcToFidu(config.getNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit)));
}
function doUSDCTransfer(
address from,
address to,
uint256 amount
) internal returns (bool) {
require(to != address(0), "Can't send to zero address");
IERC20withDec usdc = config.getUSDC();
return usdc.transferFrom(from, to, amount);
}
function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal returns (uint256 userAmount) {
IFidu fidu = config.getFidu();
// Determine current shares the address has and the shares requested to withdraw
uint256 currentShares = fidu.balanceOf(msg.sender);
// Ensure the address has enough value in the pool
require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns");
uint256 reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator());
userAmount = usdcAmount.sub(reserveAmount);
emit WithdrawalMade(msg.sender, userAmount, reserveAmount);
// Send the amounts
bool success = doUSDCTransfer(address(this), msg.sender, userAmount);
require(success, "Failed to transfer for withdraw");
sendToReserve(reserveAmount, msg.sender);
// Burn the shares
fidu.burnFrom(msg.sender, withdrawShares);
return userAmount;
}
function sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal {
// Our current design requires we re-normalize by withdrawing everything and recognizing interest gains
// before we can add additional capital to Compound
require(compoundBalance == 0, "Cannot sweep when we already have a compound balance");
require(usdcAmount != 0, "Amount to sweep cannot be zero");
uint256 error = cUSDC.mint(usdcAmount);
require(error == 0, "Sweep to compound failed");
compoundBalance = usdcAmount;
}
function _sweepFromCompound() internal {
ICUSDCContract cUSDC = config.getCUSDCContract();
sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this)));
}
function sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal {
uint256 cBalance = compoundBalance;
require(cBalance != 0, "No funds on compound");
require(cUSDCAmount != 0, "Amount to sweep cannot be zero");
IERC20 usdc = config.getUSDC();
uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this));
uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent();
uint256 redeemedUSDC = cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount);
uint256 error = cUSDC.redeem(cUSDCAmount);
uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this));
require(error == 0, "Sweep from compound failed");
require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount");
uint256 interestAccrued = redeemedUSDC.sub(cBalance);
uint256 reserveAmount = interestAccrued.div(config.getReserveDenominator());
uint256 poolAmount = interestAccrued.sub(reserveAmount);
_collectInterestAndPrincipal(address(this), poolAmount, 0);
if (reserveAmount > 0) {
sendToReserve(reserveAmount, address(cUSDC));
}
compoundBalance = 0;
}
function cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) {
// See https://compound.finance/docs#protocol-math
// But note, the docs and reality do not agree. Docs imply that that exchange rate is
// scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16
// 1e16 is also what Sheraz at Certik said.
uint256 usdcDecimals = 6;
uint256 cUSDCDecimals = 8;
// We multiply in the following order, for the following reasons...
// Amount in cToken (1e8)
// Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are)
// Downscale to cToken decimals (1e8)
// Downscale from cToken to USDC decimals (8 to 6)
return amount.mul(exchangeRate).div(10**(18 + usdcDecimals - cUSDCDecimals)).div(10**2);
}
function _collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) internal {
uint256 increment = usdcToSharePrice(interest);
sharePrice = sharePrice.add(increment);
if (interest > 0) {
emit InterestCollected(from, interest);
}
if (principal > 0) {
emit PrincipalCollected(from, principal);
totalLoansOutstanding = totalLoansOutstanding.sub(principal);
}
}
function sendToReserve(uint256 amount, address userForEvent) internal {
emit ReserveFundsCollected(userForEvent, amount);
bool success = doUSDCTransfer(address(this), config.reserveAddress(), amount);
require(success, "Reserve transfer was not successful");
}
function usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) {
return usdcToFidu(usdcAmount).mul(fiduMantissa()).div(totalShares());
}
function totalShares() internal view returns (uint256) {
return config.getFidu().totalSupply();
}
function validPool(ITranchedPool pool) internal view returns (bool) {
return config.getPoolTokens().validPool(address(pool));
}
function approvePool(ITranchedPool pool, uint256 allowance) internal {
IERC20withDec usdc = config.getUSDC();
bool success = usdc.approve(address(pool), allowance);
require(success, "Failed to approve USDC");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/SeniorPool.sol";
contract TestSeniorPool is SeniorPool {
function _getNumShares(uint256 amount) public view returns (uint256) {
return getNumShares(amount);
}
function _usdcMantissa() public pure returns (uint256) {
return usdcMantissa();
}
function _fiduMantissa() public pure returns (uint256) {
return fiduMantissa();
}
function _usdcToFidu(uint256 amount) public pure returns (uint256) {
return usdcToFidu(amount);
}
function _setSharePrice(uint256 newSharePrice) public returns (uint256) {
sharePrice = newSharePrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "../external/ERC721PresetMinterPauserAutoId.sol";
import "../interfaces/IERC20withDec.sol";
import "../interfaces/ICommunityRewards.sol";
import "../protocol/core/GoldfinchConfig.sol";
import "../protocol/core/ConfigHelper.sol";
import "../library/CommunityRewardsVesting.sol";
contract CommunityRewards is ICommunityRewards, ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20withDec;
using ConfigHelper for GoldfinchConfig;
using CommunityRewardsVesting for CommunityRewardsVesting.Rewards;
/* ========== EVENTS ========== */
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/* ========== STATE VARIABLES ========== */
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
bytes32 public constant DISTRIBUTOR_ROLE = keccak256("DISTRIBUTOR_ROLE");
GoldfinchConfig public config;
/// @notice Total rewards available for granting, denominated in `rewardsToken()`
uint256 public rewardsAvailable;
/// @notice Token launch time in seconds. This is used in vesting.
uint256 public tokenLaunchTimeInSeconds;
/// @dev NFT tokenId => rewards grant
mapping(uint256 => CommunityRewardsVesting.Rewards) public grants;
// solhint-disable-next-line func-name-mixedcase
function __initialize__(
address owner,
GoldfinchConfig _config,
uint256 _tokenLaunchTimeInSeconds
) external initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained("Goldfinch V2 Community Rewards Tokens", "GFI-V2-CR");
__ERC721Pausable_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setupRole(DISTRIBUTOR_ROLE, owner);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(DISTRIBUTOR_ROLE, OWNER_ROLE);
tokenLaunchTimeInSeconds = _tokenLaunchTimeInSeconds;
config = _config;
}
/* ========== VIEWS ========== */
/// @notice The token being disbursed as rewards
function rewardsToken() public view override returns (IERC20withDec) {
return config.getGFI();
}
/// @notice Returns the rewards claimable by a given grant token, taking into
/// account vesting schedule.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function claimableRewards(uint256 tokenId) public view override returns (uint256 rewards) {
return grants[tokenId].claimable();
}
/// @notice Returns the rewards that will have vested for some grant with the given params.
/// @return rewards Amount of rewards denominated in `rewardsToken()`
function totalVestedAt(
uint256 start,
uint256 end,
uint256 granted,
uint256 cliffLength,
uint256 vestingInterval,
uint256 revokedAt,
uint256 time
) external pure override returns (uint256 rewards) {
return CommunityRewardsVesting.getTotalVestedAt(start, end, granted, cliffLength, vestingInterval, revokedAt, time);
}
/* ========== MUTATIVE, ADMIN-ONLY FUNCTIONS ========== */
/// @notice Transfer rewards from msg.sender, to be used for reward distribution
function loadRewards(uint256 rewards) external override onlyAdmin {
require(rewards > 0, "Cannot load 0 rewards");
rewardsAvailable = rewardsAvailable.add(rewards);
rewardsToken().safeTransferFrom(msg.sender, address(this), rewards);
emit RewardAdded(rewards);
}
/// @notice Revokes rewards that have not yet vested, for a grant. The unvested rewards are
/// now considered available for allocation in another grant.
/// @param tokenId The tokenId corresponding to the grant whose unvested rewards to revoke.
function revokeGrant(uint256 tokenId) external override whenNotPaused onlyAdmin {
CommunityRewardsVesting.Rewards storage grant = grants[tokenId];
require(grant.totalGranted > 0, "Grant not defined for token id");
require(grant.revokedAt == 0, "Grant has already been revoked");
uint256 totalUnvested = grant.totalUnvestedAt(block.timestamp);
require(totalUnvested > 0, "Grant has fully vested");
rewardsAvailable = rewardsAvailable.add(totalUnvested);
grant.revokedAt = block.timestamp;
emit GrantRevoked(tokenId, totalUnvested);
}
function setTokenLaunchTimeInSeconds(uint256 _tokenLaunchTimeInSeconds) external onlyAdmin {
tokenLaunchTimeInSeconds = _tokenLaunchTimeInSeconds;
}
/// @notice updates current config
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(_msgSender(), address(config));
}
/* ========== MUTATIVE, NON-ADMIN-ONLY FUNCTIONS ========== */
/// @notice Grant rewards to a recipient. The recipient address receives an
/// an NFT representing their rewards grant. They can present the NFT to `getReward()`
/// to claim their rewards. Rewards vest over a schedule.
/// @param recipient The recipient of the grant.
/// @param amount The amount of `rewardsToken()` to grant.
/// @param vestingLength The duration (in seconds) over which the grant vests.
/// @param cliffLength The duration (in seconds) from the start of the grant, before which has elapsed
/// the vested amount remains 0.
/// @param vestingInterval The interval (in seconds) at which vesting occurs. Must be a factor of `vestingLength`.
function grant(
address recipient,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
) external override nonReentrant whenNotPaused onlyDistributor returns (uint256 tokenId) {
return _grant(recipient, amount, vestingLength, cliffLength, vestingInterval);
}
function _grant(
address recipient,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
) internal returns (uint256 tokenId) {
require(amount > 0, "Cannot grant 0 amount");
require(cliffLength <= vestingLength, "Cliff length cannot exceed vesting length");
require(vestingLength.mod(vestingInterval) == 0, "Vesting interval must be a factor of vesting length");
require(amount <= rewardsAvailable, "Cannot grant amount due to insufficient funds");
rewardsAvailable = rewardsAvailable.sub(amount);
_tokenIdTracker.increment();
tokenId = _tokenIdTracker.current();
grants[tokenId] = CommunityRewardsVesting.Rewards({
totalGranted: amount,
totalClaimed: 0,
startTime: tokenLaunchTimeInSeconds,
endTime: tokenLaunchTimeInSeconds.add(vestingLength),
cliffLength: cliffLength,
vestingInterval: vestingInterval,
revokedAt: 0
});
_mint(recipient, tokenId);
emit Granted(recipient, tokenId, amount, vestingLength, cliffLength, vestingInterval);
return tokenId;
}
/// @notice Claim rewards for a given grant
/// @param tokenId A grant token ID
function getReward(uint256 tokenId) external override nonReentrant whenNotPaused {
require(ownerOf(tokenId) == msg.sender, "access denied");
uint256 reward = claimableRewards(tokenId);
if (reward > 0) {
grants[tokenId].claim(reward);
rewardsToken().safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, tokenId, reward);
}
}
/* ========== MODIFIERS ========== */
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
function isDistributor() public view returns (bool) {
return hasRole(DISTRIBUTOR_ROLE, _msgSender());
}
modifier onlyDistributor() {
require(isDistributor(), "Must have distributor role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol";
import "../interfaces/IERC20withDec.sol";
interface ICommunityRewards is IERC721 {
function rewardsToken() external view returns (IERC20withDec);
function claimableRewards(uint256 tokenId) external view returns (uint256 rewards);
function totalVestedAt(
uint256 start,
uint256 end,
uint256 granted,
uint256 cliffLength,
uint256 vestingInterval,
uint256 revokedAt,
uint256 time
) external pure returns (uint256 rewards);
function grant(
address recipient,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
) external returns (uint256 tokenId);
function loadRewards(uint256 rewards) external;
function revokeGrant(uint256 tokenId) external;
function getReward(uint256 tokenId) external;
event RewardAdded(uint256 reward);
event Granted(
address indexed user,
uint256 indexed tokenId,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
);
event GrantRevoked(uint256 indexed tokenId, uint256 totalUnvested);
event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
library CommunityRewardsVesting {
using SafeMath for uint256;
using CommunityRewardsVesting for Rewards;
/// @dev All time values in the Rewards struct (i.e. `startTime`, `endTime`,
/// `cliffLength`, `vestingInterval`, `revokedAt`) use the same units: seconds. All timestamp
/// values (i.e. `startTime`, `endTime`, `revokedAt`) are seconds since the unix epoch.
/// @dev `cliffLength` is the duration from the start of the grant, before which has elapsed
/// the vested amount remains 0.
/// @dev `vestingInterval` is the interval at which vesting occurs. For rewards to have
/// vested fully only at `endTime`, `vestingInterval` must be a factor of
/// `endTime.sub(startTime)`. If `vestingInterval` is not thusly a factor, the calculation
/// of `totalVestedAt()` would calculate rewards to have fully vested as of the time of the
/// last whole `vestingInterval`'s elapsing before `endTime`.
struct Rewards {
uint256 totalGranted;
uint256 totalClaimed;
uint256 startTime;
uint256 endTime;
uint256 cliffLength;
uint256 vestingInterval;
uint256 revokedAt;
}
function claim(Rewards storage rewards, uint256 reward) internal {
rewards.totalClaimed = rewards.totalClaimed.add(reward);
}
function claimable(Rewards storage rewards) internal view returns (uint256) {
return claimable(rewards, block.timestamp);
}
function claimable(Rewards storage rewards, uint256 time) internal view returns (uint256) {
return rewards.totalVestedAt(time).sub(rewards.totalClaimed);
}
function totalUnvestedAt(Rewards storage rewards, uint256 time) internal view returns (uint256) {
return rewards.totalGranted.sub(rewards.totalVestedAt(time));
}
function totalVestedAt(Rewards storage rewards, uint256 time) internal view returns (uint256) {
return
getTotalVestedAt(
rewards.startTime,
rewards.endTime,
rewards.totalGranted,
rewards.cliffLength,
rewards.vestingInterval,
rewards.revokedAt,
time
);
}
function getTotalVestedAt(
uint256 start,
uint256 end,
uint256 granted,
uint256 cliffLength,
uint256 vestingInterval,
uint256 revokedAt,
uint256 time
) internal pure returns (uint256) {
if (time < start.add(cliffLength)) {
return 0;
}
if (end <= start) {
return granted;
}
uint256 elapsedVestingTimestamp = revokedAt > 0 ? Math.min(revokedAt, time) : time;
uint256 elapsedVestingUnits = (elapsedVestingTimestamp.sub(start)).div(vestingInterval);
uint256 totalVestingUnits = (end.sub(start)).div(vestingInterval);
return Math.min(granted.mul(elapsedVestingUnits).div(totalVestingUnits), granted);
}
}
// SPDX-License-Identifier: GPL-3.0-only
// solhint-disable-next-line max-line-length
// Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/MerkleDistributor.sol.
pragma solidity 0.6.12;
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "../interfaces/ICommunityRewards.sol";
import "../interfaces/IMerkleDistributor.sol";
contract MerkleDistributor is IMerkleDistributor {
address public immutable override communityRewards;
bytes32 public immutable override merkleRoot;
// @dev This is a packed array of booleans.
mapping(uint256 => uint256) private acceptedBitMap;
constructor(address communityRewards_, bytes32 merkleRoot_) public {
require(communityRewards_ != address(0), "Cannot use the null address");
require(merkleRoot_ != 0, "Invalid merkle root provided");
communityRewards = communityRewards_;
merkleRoot = merkleRoot_;
}
function isGrantAccepted(uint256 index) public view override returns (bool) {
uint256 acceptedWordIndex = index / 256;
uint256 acceptedBitIndex = index % 256;
uint256 acceptedWord = acceptedBitMap[acceptedWordIndex];
uint256 mask = (1 << acceptedBitIndex);
return acceptedWord & mask == mask;
}
function _setGrantAccepted(uint256 index) private {
uint256 acceptedWordIndex = index / 256;
uint256 acceptedBitIndex = index % 256;
acceptedBitMap[acceptedWordIndex] = acceptedBitMap[acceptedWordIndex] | (1 << acceptedBitIndex);
}
function acceptGrant(
uint256 index,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval,
bytes32[] calldata merkleProof
) external override {
require(!isGrantAccepted(index), "Grant already accepted");
// Verify the merkle proof.
//
/// @dev Per the Warning in
/// https://github.com/ethereum/solidity/blob/v0.6.12/docs/abi-spec.rst#non-standard-packed-mode,
/// it is important that no more than one of the arguments to `abi.encodePacked()` here be a
/// dynamic type (see definition in
/// https://github.com/ethereum/solidity/blob/v0.6.12/docs/abi-spec.rst#formal-specification-of-the-encoding).
bytes32 node = keccak256(abi.encodePacked(index, msg.sender, amount, vestingLength, cliffLength, vestingInterval));
require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof");
// Mark it accepted and perform the granting.
_setGrantAccepted(index);
uint256 tokenId = ICommunityRewards(communityRewards).grant(
msg.sender,
amount,
vestingLength,
cliffLength,
vestingInterval
);
emit GrantAccepted(tokenId, index, msg.sender, amount, vestingLength, cliffLength, vestingInterval);
}
}
// SPDX-License-Identifier: GPL-3.0-only
// solhint-disable-next-line max-line-length
// Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/interfaces/IMerkleDistributor.sol.
pragma solidity 0.6.12;
/// @notice Enables the granting of a CommunityRewards grant, if the grant details exist in this
/// contract's Merkle root.
interface IMerkleDistributor {
/// @notice Returns the address of the CommunityRewards contract whose grants are distributed by this contract.
function communityRewards() external view returns (address);
/// @notice Returns the merkle root of the merkle tree containing grant details available to accept.
function merkleRoot() external view returns (bytes32);
/// @notice Returns true if the index has been marked accepted.
function isGrantAccepted(uint256 index) external view returns (bool);
/// @notice Causes the sender to accept the grant consisting of the given details. Reverts if
/// the inputs (which includes who the sender is) are invalid.
function acceptGrant(
uint256 index,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval,
bytes32[] calldata merkleProof
) external;
/// @notice This event is triggered whenever a call to #acceptGrant succeeds.
event GrantAccepted(
uint256 indexed tokenId,
uint256 indexed index,
address indexed account,
uint256 amount,
uint256 vestingLength,
uint256 cliffLength,
uint256 vestingInterval
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../core/BaseUpgradeablePausable.sol";
import "../core/ConfigHelper.sol";
import "../core/CreditLine.sol";
import "../core/GoldfinchConfig.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IBorrower.sol";
import "@opengsn/gsn/contracts/BaseRelayRecipient.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title Goldfinch's Borrower contract
* @notice These contracts represent the a convenient way for a borrower to interact with Goldfinch
* They are 100% optional. However, they let us add many sophisticated and convient features for borrowers
* while still keeping our core protocol small and secure. We therefore expect most borrowers will use them.
* This contract is the "official" borrower contract that will be maintained by Goldfinch governance. However,
* in theory, anyone can fork or create their own version, or not use any contract at all. The core functionality
* is completely agnostic to whether it is interacting with a contract or an externally owned account (EOA).
* @author Goldfinch
*/
contract Borrower is BaseUpgradeablePausable, BaseRelayRecipient, IBorrower {
using SafeMath for uint256;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
address private constant USDT_ADDRESS = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);
address private constant BUSD_ADDRESS = address(0x4Fabb145d64652a948d72533023f6E7A623C7C53);
address private constant GUSD_ADDRESS = address(0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd);
address private constant DAI_ADDRESS = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
function initialize(address owner, address _config) external override initializer {
require(owner != address(0) && _config != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = GoldfinchConfig(_config);
trustedForwarder = config.trustedForwarderAddress();
// Handle default approvals. Pool, and OneInch for maximum amounts
address oneInch = config.oneInchAddress();
IERC20withDec usdc = config.getUSDC();
usdc.approve(oneInch, uint256(-1));
bytes memory data = abi.encodeWithSignature("approve(address,uint256)", oneInch, uint256(-1));
invoke(USDT_ADDRESS, data);
invoke(BUSD_ADDRESS, data);
invoke(GUSD_ADDRESS, data);
invoke(DAI_ADDRESS, data);
}
function lockJuniorCapital(address poolAddress) external onlyAdmin {
ITranchedPool(poolAddress).lockJuniorCapital();
}
function lockPool(address poolAddress) external onlyAdmin {
ITranchedPool(poolAddress).lockPool();
}
/**
* @notice Allows a borrower to drawdown on their creditline through the CreditDesk.
* @param poolAddress The creditline from which they would like to drawdown
* @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown
* @param addressToSendTo The address where they would like the funds sent. If the zero address is passed,
* it will be defaulted to the contracts address (msg.sender). This is a convenience feature for when they would
* like the funds sent to an exchange or alternate wallet, different from the authentication address
*/
function drawdown(
address poolAddress,
uint256 amount,
address addressToSendTo
) external onlyAdmin {
ITranchedPool(poolAddress).drawdown(amount);
if (addressToSendTo == address(0) || addressToSendTo == address(this)) {
addressToSendTo = _msgSender();
}
transferERC20(config.usdcAddress(), addressToSendTo, amount);
}
function drawdownWithSwapOnOneInch(
address poolAddress,
uint256 amount,
address addressToSendTo,
address toToken,
uint256 minTargetAmount,
uint256[] calldata exchangeDistribution
) public onlyAdmin {
// Drawdown to the Borrower contract
ITranchedPool(poolAddress).drawdown(amount);
// Do the swap
swapOnOneInch(config.usdcAddress(), toToken, amount, minTargetAmount, exchangeDistribution);
// Default to sending to the owner, and don't let funds stay in this contract
if (addressToSendTo == address(0) || addressToSendTo == address(this)) {
addressToSendTo = _msgSender();
}
// Fulfill the send to
bytes memory _data = abi.encodeWithSignature("balanceOf(address)", address(this));
uint256 receivedAmount = toUint256(invoke(toToken, _data));
transferERC20(toToken, addressToSendTo, receivedAmount);
}
function transferERC20(
address token,
address to,
uint256 amount
) public onlyAdmin {
bytes memory _data = abi.encodeWithSignature("transfer(address,uint256)", to, amount);
invoke(token, _data);
}
/**
* @notice Allows a borrower to payback loans by calling the `pay` function directly on the CreditDesk
* @param poolAddress The credit line to be paid back
* @param amount The amount, in USDC atomic units, that the borrower wishes to pay
*/
function pay(address poolAddress, uint256 amount) external onlyAdmin {
IERC20withDec usdc = config.getUSDC();
bool success = usdc.transferFrom(_msgSender(), address(this), amount);
require(success, "Failed to transfer USDC");
_transferAndPay(usdc, poolAddress, amount);
}
function payMultiple(address[] calldata pools, uint256[] calldata amounts) external onlyAdmin {
require(pools.length == amounts.length, "Pools and amounts must be the same length");
uint256 totalAmount;
for (uint256 i = 0; i < amounts.length; i++) {
totalAmount = totalAmount.add(amounts[i]);
}
IERC20withDec usdc = config.getUSDC();
// Do a single transfer, which is cheaper
bool success = usdc.transferFrom(_msgSender(), address(this), totalAmount);
require(success, "Failed to transfer USDC");
for (uint256 i = 0; i < amounts.length; i++) {
_transferAndPay(usdc, pools[i], amounts[i]);
}
}
function payInFull(address poolAddress, uint256 amount) external onlyAdmin {
IERC20withDec usdc = config.getUSDC();
bool success = usdc.transferFrom(_msgSender(), address(this), amount);
require(success, "Failed to transfer USDC");
_transferAndPay(usdc, poolAddress, amount);
require(ITranchedPool(poolAddress).creditLine().balance() == 0, "Failed to fully pay off creditline");
}
function payWithSwapOnOneInch(
address poolAddress,
uint256 originAmount,
address fromToken,
uint256 minTargetAmount,
uint256[] calldata exchangeDistribution
) external onlyAdmin {
transferFrom(fromToken, _msgSender(), address(this), originAmount);
IERC20withDec usdc = config.getUSDC();
swapOnOneInch(fromToken, address(usdc), originAmount, minTargetAmount, exchangeDistribution);
uint256 usdcBalance = usdc.balanceOf(address(this));
_transferAndPay(usdc, poolAddress, usdcBalance);
}
function payMultipleWithSwapOnOneInch(
address[] calldata pools,
uint256[] calldata minAmounts,
uint256 originAmount,
address fromToken,
uint256[] calldata exchangeDistribution
) external onlyAdmin {
require(pools.length == minAmounts.length, "Pools and amounts must be the same length");
uint256 totalMinAmount = 0;
for (uint256 i = 0; i < minAmounts.length; i++) {
totalMinAmount = totalMinAmount.add(minAmounts[i]);
}
transferFrom(fromToken, _msgSender(), address(this), originAmount);
IERC20withDec usdc = config.getUSDC();
swapOnOneInch(fromToken, address(usdc), originAmount, totalMinAmount, exchangeDistribution);
for (uint256 i = 0; i < minAmounts.length; i++) {
_transferAndPay(usdc, pools[i], minAmounts[i]);
}
uint256 remainingUSDC = usdc.balanceOf(address(this));
if (remainingUSDC > 0) {
_transferAndPay(usdc, pools[0], remainingUSDC);
}
}
function _transferAndPay(
IERC20withDec usdc,
address poolAddress,
uint256 amount
) internal {
ITranchedPool pool = ITranchedPool(poolAddress);
// We don't use transferFrom since it would require a separate approval per creditline
bool success = usdc.transfer(address(pool.creditLine()), amount);
require(success, "USDC Transfer to creditline failed");
pool.assess();
}
function transferFrom(
address erc20,
address sender,
address recipient,
uint256 amount
) internal {
bytes memory _data;
// Do a low-level invoke on this transfer, since Tether fails if we use the normal IERC20 interface
_data = abi.encodeWithSignature("transferFrom(address,address,uint256)", sender, recipient, amount);
invoke(address(erc20), _data);
}
function swapOnOneInch(
address fromToken,
address toToken,
uint256 originAmount,
uint256 minTargetAmount,
uint256[] calldata exchangeDistribution
) internal {
bytes memory _data = abi.encodeWithSignature(
"swap(address,address,uint256,uint256,uint256[],uint256)",
fromToken,
toToken,
originAmount,
minTargetAmount,
exchangeDistribution,
0
);
invoke(config.oneInchAddress(), _data);
}
/**
* @notice Performs a generic transaction.
* @param _target The address for the transaction.
* @param _data The data of the transaction.
* Mostly copied from Argent:
* https://github.com/argentlabs/argent-contracts/blob/develop/contracts/wallet/BaseWallet.sol#L111
*/
function invoke(address _target, bytes memory _data) internal returns (bytes memory) {
// External contracts can be compiled with different Solidity versions
// which can cause "revert without reason" when called through,
// for example, a standard IERC20 ABI compiled on the latest version.
// This low-level call avoids that issue.
bool success;
bytes memory _res;
// solhint-disable-next-line avoid-low-level-calls
(success, _res) = _target.call(_data);
if (!success && _res.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
} else if (!success) {
revert("VM: wallet invoke reverted");
}
return _res;
}
function toUint256(bytes memory _bytes) internal pure returns (uint256 value) {
assembly {
value := mload(add(_bytes, 0x20))
}
}
// OpenZeppelin contracts come with support for GSN _msgSender() (which just defaults to msg.sender)
// Since there are two different versions of the function in the hierarchy, we need to instruct solidity to
// use the relay recipient version which can actually pull the real sender from the parameters.
// https://www.notion.so/My-contract-is-using-OpenZeppelin-How-do-I-add-GSN-support-2bee7e9d5f774a0cbb60d3a8de03e9fb
function _msgSender() internal view override(ContextUpgradeSafe, BaseRelayRecipient) returns (address payable) {
return BaseRelayRecipient._msgSender();
}
function _msgData() internal view override(ContextUpgradeSafe, BaseRelayRecipient) returns (bytes memory ret) {
return BaseRelayRecipient._msgData();
}
function versionRecipient() external view override returns (string memory) {
return "2.0.0";
}
}
// SPDX-Licence-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IBorrower {
function initialize(address owner, address _config) external;
}
// SPDX-License-Identifier:MIT
// solhint-disable no-inline-assembly
pragma solidity ^0.6.2;
import "./interfaces/IRelayRecipient.sol";
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
abstract contract BaseRelayRecipient is IRelayRecipient {
/*
* Forwarder singleton we accept calls from
*/
address public trustedForwarder;
function isTrustedForwarder(address forwarder) public override view returns(bool) {
return forwarder == trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal override virtual view returns (address payable ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
assembly {
ret := shr(96,calldataload(sub(calldatasize(),20)))
}
} else {
return msg.sender;
}
}
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal override virtual view returns (bytes memory ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// we copy the msg.data , except the last 20 bytes (and update the total length)
assembly {
let ptr := mload(0x40)
// copy only size-20 bytes
let size := sub(calldatasize(),20)
// structure RLP data as <offset> <length> <bytes>
mstore(ptr, 0x20)
mstore(add(ptr,32), size)
calldatacopy(add(ptr,64), 0, size)
return(ptr, add(size,64))
}
} else {
return msg.data;
}
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.6.2;
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return if the forwarder is trusted to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function isTrustedForwarder(address forwarder) public virtual view returns(bool);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal virtual view returns (address payable);
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal virtual view returns (bytes memory);
function versionRecipient() external virtual view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "./BaseUpgradeablePausable.sol";
import "../../interfaces/IBorrower.sol";
import "../../interfaces/ITranchedPool.sol";
import "./ConfigHelper.sol";
/**
* @title GoldfinchFactory
* @notice Contract that allows us to create other contracts, such as CreditLines and BorrowerContracts
* Note GoldfinchFactory is a legacy name. More properly this can be considered simply the GoldfinchFactory
* @author Goldfinch
*/
contract GoldfinchFactory is BaseUpgradeablePausable {
GoldfinchConfig public config;
/// Role to allow for pool creation
bytes32 public constant BORROWER_ROLE = keccak256("BORROWER_ROLE");
using ConfigHelper for GoldfinchConfig;
event BorrowerCreated(address indexed borrower, address indexed owner);
event PoolCreated(address indexed pool, address indexed borrower);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
event CreditLineCreated(address indexed creditLine);
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
_performUpgrade();
}
function performUpgrade() external onlyAdmin {
_performUpgrade();
}
function _performUpgrade() internal {
if (getRoleAdmin(BORROWER_ROLE) != OWNER_ROLE) {
_setRoleAdmin(BORROWER_ROLE, OWNER_ROLE);
}
}
/**
* @notice Allows anyone to create a CreditLine contract instance
* @dev There is no value to calling this function directly. It is only meant to be called
* by a TranchedPool during it's creation process.
*/
function createCreditLine() external returns (address) {
address creditLine = deployMinimal(config.creditLineImplementationAddress());
emit CreditLineCreated(creditLine);
return creditLine;
}
/**
* @notice Allows anyone to create a Borrower contract instance
* @param owner The address that will own the new Borrower instance
*/
function createBorrower(address owner) external returns (address) {
address _borrower = deployMinimal(config.borrowerImplementationAddress());
IBorrower borrower = IBorrower(_borrower);
borrower.initialize(owner, address(config));
emit BorrowerCreated(address(borrower), owner);
return address(borrower);
}
/**
* @notice Allows anyone to create a new TranchedPool for a single borrower
* @param _borrower The borrower for whom the CreditLine will be created
* @param _juniorFeePercent The percent of senior interest allocated to junior investors, expressed as
* integer percents. eg. 20% is simply 20
* @param _limit The maximum amount a borrower can drawdown from this CreditLine
* @param _interestApr The interest amount, on an annualized basis (APR, so non-compounding), expressed as an integer.
* We assume 18 digits of precision. For example, to submit 15.34%, you would pass up 153400000000000000,
* and 5.34% would be 53400000000000000
* @param _paymentPeriodInDays How many days in each payment period.
* ie. the frequency with which they need to make payments.
* @param _termInDays Number of days in the credit term. It is used to set the `termEndTime` upon first drawdown.
* ie. The credit line should be fully paid off {_termIndays} days after the first drawdown.
* @param _lateFeeApr The additional interest you will pay if you are late. For example, if this is 3%, and your
* normal rate is 15%, then you will pay 18% while you are late. Also expressed as an 18 decimal precision integer
*
* Requirements:
* You are the admin
*/
function createPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) external onlyAdminOrBorrower returns (address pool) {
address tranchedPoolImplAddress = config.tranchedPoolAddress();
pool = deployMinimal(tranchedPoolImplAddress);
ITranchedPool(pool).initialize(
address(config),
_borrower,
_juniorFeePercent,
_limit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays,
_fundableAt,
_allowedUIDTypes
);
emit PoolCreated(pool, _borrower);
config.getPoolTokens().onPoolCreated(pool);
return pool;
}
function createMigratedPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) external onlyCreditDesk returns (address pool) {
address tranchedPoolImplAddress = config.migratedTranchedPoolAddress();
pool = deployMinimal(tranchedPoolImplAddress);
ITranchedPool(pool).initialize(
address(config),
_borrower,
_juniorFeePercent,
_limit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr,
_principalGracePeriodInDays,
_fundableAt,
_allowedUIDTypes
);
emit PoolCreated(pool, _borrower);
config.getPoolTokens().onPoolCreated(pool);
return pool;
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
// Stolen from:
// https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/ProxyFactory.sol
function deployMinimal(address _logic) internal returns (address proxy) {
bytes20 targetBytes = bytes20(_logic);
// solhint-disable-next-line no-inline-assembly
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create(0, clone, 0x37)
}
return proxy;
}
function isBorrower() public view returns (bool) {
return hasRole(BORROWER_ROLE, _msgSender());
}
modifier onlyAdminOrBorrower() {
require(isAdmin() || isBorrower(), "Must have admin or borrower role to perform this action");
_;
}
modifier onlyCreditDesk() {
require(msg.sender == config.creditDeskAddress(), "Only the CreditDesk can call this");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
import "../library/SafeERC20Transfer.sol";
import "../protocol/core/ConfigHelper.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
import "../interfaces/IPoolTokens.sol";
import "../interfaces/ITranchedPool.sol";
import "../interfaces/IBackerRewards.sol";
// Basically, Every time a interest payment comes back
// we keep a running total of dollars (totalInterestReceived) until it reaches the maxInterestDollarsEligible limit
// Every dollar of interest received from 0->maxInterestDollarsEligible
// has a allocated amount of rewards based on a sqrt function.
// When a interest payment comes in for a given Pool or the pool balance increases
// we recalculate the pool's accRewardsPerPrincipalDollar
// equation ref `_calculateNewGrossGFIRewardsForInterestAmount()`:
// (sqrtNewTotalInterest - sqrtOrigTotalInterest) / sqrtMaxInterestDollarsEligible * (totalRewards / totalGFISupply)
// When a PoolToken is minted, we set the mint price to the pool's current accRewardsPerPrincipalDollar
// Every time a PoolToken withdraws rewards, we determine the allocated rewards,
// increase that PoolToken's rewardsClaimed, and transfer the owner the gfi
contract BackerRewards is IBackerRewards, BaseUpgradeablePausable, SafeERC20Transfer {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
using SafeMath for uint256;
struct BackerRewardsInfo {
uint256 accRewardsPerPrincipalDollar; // accumulator gfi per interest dollar
}
struct BackerRewardsTokenInfo {
uint256 rewardsClaimed; // gfi claimed
uint256 accRewardsPerPrincipalDollarAtMint; // Pool's accRewardsPerPrincipalDollar at PoolToken mint()
}
uint256 public totalRewards; // total amount of GFI rewards available, times 1e18
uint256 public maxInterestDollarsEligible; // interest $ eligible for gfi rewards, times 1e18
uint256 public totalInterestReceived; // counter of total interest repayments, times 1e6
uint256 public totalRewardPercentOfTotalGFI; // totalRewards/totalGFISupply, times 1e18
mapping(uint256 => BackerRewardsTokenInfo) public tokens; // poolTokenId -> BackerRewardsTokenInfo
mapping(address => BackerRewardsInfo) public pools; // pool.address -> BackerRewardsInfo
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
}
/**
* @notice Calculates the accRewardsPerPrincipalDollar for a given pool,
when a interest payment is received by the protocol
* @param _interestPaymentAmount The amount of total dollars the interest payment, expects 10^6 value
*/
function allocateRewards(uint256 _interestPaymentAmount) external override onlyPool {
// note: do not use a require statment because that will TranchedPool kill execution
if (_interestPaymentAmount > 0) {
_allocateRewards(_interestPaymentAmount);
}
}
/**
* @notice Set the total gfi rewards and the % of total GFI
* @param _totalRewards The amount of GFI rewards available, expects 10^18 value
*/
function setTotalRewards(uint256 _totalRewards) public onlyAdmin {
totalRewards = _totalRewards;
uint256 totalGFISupply = config.getGFI().totalSupply();
totalRewardPercentOfTotalGFI = _totalRewards.mul(mantissa()).div(totalGFISupply).mul(100);
emit BackerRewardsSetTotalRewards(_msgSender(), _totalRewards, totalRewardPercentOfTotalGFI);
}
/**
* @notice Set the total interest received to date.
This should only be called once on contract deploy.
* @param _totalInterestReceived The amount of interest the protocol has received to date, expects 10^6 value
*/
function setTotalInterestReceived(uint256 _totalInterestReceived) public onlyAdmin {
totalInterestReceived = _totalInterestReceived;
emit BackerRewardsSetTotalInterestReceived(_msgSender(), _totalInterestReceived);
}
/**
* @notice Set the max dollars across the entire protocol that are eligible for GFI rewards
* @param _maxInterestDollarsEligible The amount of interest dollars eligible for GFI rewards, expects 10^18 value
*/
function setMaxInterestDollarsEligible(uint256 _maxInterestDollarsEligible) public onlyAdmin {
maxInterestDollarsEligible = _maxInterestDollarsEligible;
emit BackerRewardsSetMaxInterestDollarsEligible(_msgSender(), _maxInterestDollarsEligible);
}
/**
* @notice When a pool token is minted for multiple drawdowns,
set accRewardsPerPrincipalDollarAtMint to the current accRewardsPerPrincipalDollar price
* @param tokenId Pool token id
*/
function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external override {
require(_msgSender() == config.poolTokensAddress(), "Invalid sender!");
require(config.getPoolTokens().validPool(poolAddress), "Invalid pool!");
if (tokens[tokenId].accRewardsPerPrincipalDollarAtMint != 0) {
return;
}
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
require(poolAddress == tokenInfo.pool, "PoolAddress must equal PoolToken pool address");
tokens[tokenId].accRewardsPerPrincipalDollarAtMint = pools[tokenInfo.pool].accRewardsPerPrincipalDollar;
}
/**
* @notice Calculate the gross available gfi rewards for a PoolToken
* @param tokenId Pool token id
* @return The amount of GFI claimable
*/
function poolTokenClaimableRewards(uint256 tokenId) public view returns (uint256) {
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
// Note: If a TranchedPool is oversubscribed, reward allocation's scale down proportionately.
uint256 diffOfAccRewardsPerPrincipalDollar = pools[tokenInfo.pool].accRewardsPerPrincipalDollar.sub(
tokens[tokenId].accRewardsPerPrincipalDollarAtMint
);
uint256 rewardsClaimed = tokens[tokenId].rewardsClaimed.mul(mantissa());
/*
equation for token claimable rewards:
token.principalAmount
* (pool.accRewardsPerPrincipalDollar - token.accRewardsPerPrincipalDollarAtMint)
- token.rewardsClaimed
*/
return
usdcToAtomic(tokenInfo.principalAmount).mul(diffOfAccRewardsPerPrincipalDollar).sub(rewardsClaimed).div(
mantissa()
);
}
/**
* @notice PoolToken request to withdraw multiple PoolTokens allocated rewards
* @param tokenIds Array of pool token id
*/
function withdrawMultiple(uint256[] calldata tokenIds) public {
require(tokenIds.length > 0, "TokensIds length must not be 0");
for (uint256 i = 0; i < tokenIds.length; i++) {
withdraw(tokenIds[i]);
}
}
/**
* @notice PoolToken request to withdraw all allocated rewards
* @param tokenId Pool token id
*/
function withdraw(uint256 tokenId) public {
uint256 totalClaimableRewards = poolTokenClaimableRewards(tokenId);
uint256 poolTokenRewardsClaimed = tokens[tokenId].rewardsClaimed;
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
address poolAddr = tokenInfo.pool;
require(config.getPoolTokens().validPool(poolAddr), "Invalid pool!");
require(msg.sender == poolTokens.ownerOf(tokenId), "Must be owner of PoolToken");
BaseUpgradeablePausable pool = BaseUpgradeablePausable(poolAddr);
require(!pool.paused(), "Pool withdraw paused");
ITranchedPool tranchedPool = ITranchedPool(poolAddr);
require(!tranchedPool.creditLine().isLate(), "Pool is late on payments");
tokens[tokenId].rewardsClaimed = poolTokenRewardsClaimed.add(totalClaimableRewards);
safeERC20Transfer(config.getGFI(), poolTokens.ownerOf(tokenId), totalClaimableRewards);
emit BackerRewardsClaimed(_msgSender(), tokenId, totalClaimableRewards);
}
/* Internal functions */
function _allocateRewards(uint256 _interestPaymentAmount) internal {
uint256 _totalInterestReceived = totalInterestReceived;
if (usdcToAtomic(_totalInterestReceived) >= maxInterestDollarsEligible) {
return;
}
address _poolAddress = _msgSender();
// Gross GFI Rewards earned for incoming interest dollars
uint256 newGrossRewards = _calculateNewGrossGFIRewardsForInterestAmount(_interestPaymentAmount);
ITranchedPool pool = ITranchedPool(_poolAddress);
BackerRewardsInfo storage _poolInfo = pools[_poolAddress];
uint256 totalJuniorDeposits = pool.totalJuniorDeposits();
if (totalJuniorDeposits == 0) {
return;
}
// example: (6708203932437400000000 * 10^18) / (100000*10^18)
_poolInfo.accRewardsPerPrincipalDollar = _poolInfo.accRewardsPerPrincipalDollar.add(
newGrossRewards.mul(mantissa()).div(usdcToAtomic(totalJuniorDeposits))
);
totalInterestReceived = _totalInterestReceived.add(_interestPaymentAmount);
}
/**
* @notice Calculate the rewards earned for a given interest payment
* @param _interestPaymentAmount interest payment amount times 1e6
*/
function _calculateNewGrossGFIRewardsForInterestAmount(uint256 _interestPaymentAmount)
internal
view
returns (uint256)
{
uint256 totalGFISupply = config.getGFI().totalSupply();
// incoming interest payment, times * 1e18 divided by 1e6
uint256 interestPaymentAmount = usdcToAtomic(_interestPaymentAmount);
// all-time interest payments prior to the incoming amount, times 1e18
uint256 _previousTotalInterestReceived = usdcToAtomic(totalInterestReceived);
uint256 sqrtOrigTotalInterest = Babylonian.sqrt(_previousTotalInterestReceived);
// sum of new interest payment + previous total interest payments, times 1e18
uint256 newTotalInterest = usdcToAtomic(
atomicToUSDC(_previousTotalInterestReceived).add(atomicToUSDC(interestPaymentAmount))
);
// interest payment passed the maxInterestDollarsEligible cap, should only partially be rewarded
if (newTotalInterest > maxInterestDollarsEligible) {
newTotalInterest = maxInterestDollarsEligible;
}
/*
equation:
(sqrtNewTotalInterest-sqrtOrigTotalInterest)
* totalRewardPercentOfTotalGFI
/ sqrtMaxInterestDollarsEligible
/ 100
* totalGFISupply
/ 10^18
example scenario:
- new payment = 5000*10^18
- original interest received = 0*10^18
- total reward percent = 3 * 10^18
- max interest dollars = 1 * 10^27 ($1 billion)
- totalGfiSupply = 100_000_000 * 10^18
example math:
(70710678118 - 0)
* 3000000000000000000
/ 31622776601683
/ 100
* 100000000000000000000000000
/ 10^18
= 6708203932437400000000 (6,708.2039 GFI)
*/
uint256 sqrtDiff = Babylonian.sqrt(newTotalInterest).sub(sqrtOrigTotalInterest);
uint256 sqrtMaxInterestDollarsEligible = Babylonian.sqrt(maxInterestDollarsEligible);
require(sqrtMaxInterestDollarsEligible > 0, "maxInterestDollarsEligible must not be zero");
uint256 newGrossRewards = sqrtDiff
.mul(totalRewardPercentOfTotalGFI)
.div(sqrtMaxInterestDollarsEligible)
.div(100)
.mul(totalGFISupply)
.div(mantissa());
// Extra safety check to make sure the logic is capped at a ceiling of potential rewards
// Calculating the gfi/$ for first dollar of interest to the protocol, and multiplying by new interest amount
uint256 absoluteMaxGfiCheckPerDollar = Babylonian
.sqrt((uint256)(1).mul(mantissa()))
.mul(totalRewardPercentOfTotalGFI)
.div(sqrtMaxInterestDollarsEligible)
.div(100)
.mul(totalGFISupply)
.div(mantissa());
require(
newGrossRewards < absoluteMaxGfiCheckPerDollar.mul(newTotalInterest),
"newGrossRewards cannot be greater then the max gfi per dollar"
);
return newGrossRewards;
}
function mantissa() internal pure returns (uint256) {
return uint256(10)**uint256(18);
}
function usdcMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(6);
}
function usdcToAtomic(uint256 amount) internal pure returns (uint256) {
return amount.mul(mantissa()).div(usdcMantissa());
}
function atomicToUSDC(uint256 amount) internal pure returns (uint256) {
return amount.div(mantissa().div(usdcMantissa()));
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(_msgSender(), address(config));
}
/* ======== MODIFIERS ======== */
modifier onlyPool() {
require(config.getPoolTokens().validPool(_msgSender()), "Invalid pool!");
_;
}
/* ======== EVENTS ======== */
event GoldfinchConfigUpdated(address indexed who, address configAddress);
event BackerRewardsClaimed(address indexed owner, uint256 indexed tokenId, uint256 amount);
event BackerRewardsSetTotalRewards(address indexed owner, uint256 totalRewards, uint256 totalRewardPercentOfTotalGFI);
event BackerRewardsSetTotalInterestReceived(address indexed owner, uint256 totalInterestReceived);
event BackerRewardsSetMaxInterestDollarsEligible(address indexed owner, uint256 maxInterestDollarsEligible);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../rewards/BackerRewards.sol";
contract TestBackerRewards is BackerRewards {
address payable public sender;
// solhint-disable-next-line modifiers/ensure-modifiers
function _setSender(address payable _sender) public {
sender = _sender;
}
function _msgSender() internal view override returns (address payable) {
if (sender != address(0)) {
return sender;
} else {
return super._msgSender();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "../../external/ERC721PresetMinterPauserAutoId.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/IFidu.sol";
import "../core/BaseUpgradeablePausable.sol";
import "../core/GoldfinchConfig.sol";
import "../core/ConfigHelper.sol";
import "../../library/SafeERC20Transfer.sol";
contract TransferRestrictedVault is
ERC721PresetMinterPauserAutoIdUpgradeSafe,
ReentrancyGuardUpgradeSafe,
SafeERC20Transfer
{
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
using SafeMath for uint256;
struct PoolTokenPosition {
uint256 tokenId;
uint256 lockedUntil;
}
struct FiduPosition {
uint256 amount;
uint256 lockedUntil;
}
// tokenId => poolTokenPosition
mapping(uint256 => PoolTokenPosition) public poolTokenPositions;
// tokenId => fiduPosition
mapping(uint256 => FiduPosition) public fiduPositions;
/*
We are using our own initializer function so that OZ doesn't automatically
set owner as msg.sender. Also, it lets us set our config contract
*/
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) external initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__Context_init_unchained();
__AccessControl_init_unchained();
__ReentrancyGuard_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained("Goldfinch V2 Accredited Investor Tokens", "GFI-V2-AI");
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
config = _config;
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
function depositJunior(ITranchedPool tranchedPool, uint256 amount) public nonReentrant {
require(config.getGo().go(msg.sender), "This address has not been go-listed");
safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount);
approveSpender(address(tranchedPool), amount);
uint256 poolTokenId = tranchedPool.deposit(uint256(ITranchedPool.Tranches.Junior), amount);
uint256 transferRestrictionPeriodInSeconds = SECONDS_PER_DAY.mul(config.getTransferRestrictionPeriodInDays());
_tokenIdTracker.increment();
uint256 tokenId = _tokenIdTracker.current();
poolTokenPositions[tokenId] = PoolTokenPosition({
tokenId: poolTokenId,
lockedUntil: block.timestamp.add(transferRestrictionPeriodInSeconds)
});
_mint(msg.sender, tokenId);
}
function depositJuniorWithPermit(
ITranchedPool tranchedPool,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
depositJunior(tranchedPool, amount);
}
function depositSenior(uint256 amount) public nonReentrant {
safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount);
ISeniorPool seniorPool = config.getSeniorPool();
approveSpender(address(seniorPool), amount);
uint256 depositShares = seniorPool.deposit(amount);
uint256 transferRestrictionPeriodInSeconds = SECONDS_PER_DAY.mul(config.getTransferRestrictionPeriodInDays());
_tokenIdTracker.increment();
uint256 tokenId = _tokenIdTracker.current();
fiduPositions[tokenId] = FiduPosition({
amount: depositShares,
lockedUntil: block.timestamp.add(transferRestrictionPeriodInSeconds)
});
_mint(msg.sender, tokenId);
}
function depositSeniorWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s);
depositSenior(amount);
}
function withdrawSenior(uint256 tokenId, uint256 usdcAmount) public nonReentrant onlyTokenOwner(tokenId) {
IFidu fidu = config.getFidu();
ISeniorPool seniorPool = config.getSeniorPool();
uint256 fiduBalanceBefore = fidu.balanceOf(address(this));
uint256 receivedAmount = seniorPool.withdraw(usdcAmount);
uint256 fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this)));
FiduPosition storage fiduPosition = fiduPositions[tokenId];
uint256 fiduPositionAmount = fiduPosition.amount;
require(fiduPositionAmount >= fiduUsed, "Not enough Fidu for withdrawal");
fiduPosition.amount = fiduPositionAmount.sub(fiduUsed);
safeERC20Transfer(config.getUSDC(), msg.sender, receivedAmount);
}
function withdrawSeniorInFidu(uint256 tokenId, uint256 shares) public nonReentrant onlyTokenOwner(tokenId) {
FiduPosition storage fiduPosition = fiduPositions[tokenId];
uint256 fiduPositionAmount = fiduPosition.amount;
require(fiduPositionAmount >= shares, "Not enough Fidu for withdrawal");
fiduPosition.amount = fiduPositionAmount.sub(shares);
uint256 usdcAmount = config.getSeniorPool().withdrawInFidu(shares);
safeERC20Transfer(config.getUSDC(), msg.sender, usdcAmount);
}
function withdrawJunior(uint256 tokenId, uint256 amount)
public
nonReentrant
onlyTokenOwner(tokenId)
returns (uint256 interestWithdrawn, uint256 principalWithdrawn)
{
PoolTokenPosition storage position = poolTokenPositions[tokenId];
require(position.lockedUntil > 0, "Position is empty");
IPoolTokens poolTokens = config.getPoolTokens();
uint256 poolTokenId = position.tokenId;
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(poolTokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
(interestWithdrawn, principalWithdrawn) = pool.withdraw(poolTokenId, amount);
uint256 totalWithdrawn = interestWithdrawn.add(principalWithdrawn);
safeERC20Transfer(config.getUSDC(), msg.sender, totalWithdrawn);
return (interestWithdrawn, principalWithdrawn);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId // solhint-disable-line no-unused-vars
) internal virtual override(ERC721PresetMinterPauserAutoIdUpgradeSafe) {
// AccreditedInvestor tokens can never be transferred. The underlying positions,
// however, can be transferred after the timelock expires.
require(from == address(0) || to == address(0), "TransferRestrictedVault tokens cannot be transferred");
}
/**
* @dev This method assumes that positions are mutually exclusive i.e. that the token
* represents a position in either PoolTokens or Fidu, but not both.
*/
function transferPosition(uint256 tokenId, address to) public nonReentrant {
require(ownerOf(tokenId) == msg.sender, "Cannot transfer position of token you don't own");
FiduPosition storage fiduPosition = fiduPositions[tokenId];
if (fiduPosition.lockedUntil > 0) {
require(
block.timestamp >= fiduPosition.lockedUntil,
"Underlying position cannot be transferred until lockedUntil"
);
transferFiduPosition(fiduPosition, to);
delete fiduPositions[tokenId];
}
PoolTokenPosition storage poolTokenPosition = poolTokenPositions[tokenId];
if (poolTokenPosition.lockedUntil > 0) {
require(
block.timestamp >= poolTokenPosition.lockedUntil,
"Underlying position cannot be transferred until lockedUntil"
);
transferPoolTokenPosition(poolTokenPosition, to);
delete poolTokenPositions[tokenId];
}
_burn(tokenId);
}
function transferPoolTokenPosition(PoolTokenPosition storage position, address to) internal {
IPoolTokens poolTokens = config.getPoolTokens();
poolTokens.safeTransferFrom(address(this), to, position.tokenId);
}
function transferFiduPosition(FiduPosition storage position, address to) internal {
IFidu fidu = config.getFidu();
safeERC20Transfer(fidu, to, position.amount);
}
function approveSpender(address spender, uint256 allowance) internal {
IERC20withDec usdc = config.getUSDC();
safeERC20Approve(usdc, spender, allowance);
}
modifier onlyTokenOwner(uint256 tokenId) {
require(ownerOf(tokenId) == msg.sender, "Only the token owner is allowed to call this function");
_;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
// contract IOneSplitConsts {
// // flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ...
// uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01;
// uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated
// uint256 internal constant FLAG_DISABLE_BANCOR = 0x04;
// uint256 internal constant FLAG_DISABLE_OASIS = 0x08;
// uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10;
// uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20;
// uint256 internal constant FLAG_DISABLE_CHAI = 0x40;
// uint256 internal constant FLAG_DISABLE_AAVE = 0x80;
// uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100;
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default
// uint256 internal constant FLAG_DISABLE_BDAI = 0x400;
// uint256 internal constant FLAG_DISABLE_IEARN = 0x800;
// uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
// uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000;
// uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000;
// uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default
// uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
// uint256 internal constant FLAG_DISABLE_WETH = 0x80000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
// uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
// uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
// uint256 internal constant FLAG_DISABLE_IDLE = 0x800000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000;
// uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000;
// uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000;
// uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000;
// uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000;
// uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000;
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default
// uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000;
// uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000;
// uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000;
// uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000;
// uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000;
// uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000;
// uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000;
// uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000;
// uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000;
// uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000;
// uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000;
// uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000;
// uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000;
// uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default
// uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default
// uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default
// uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000;
// uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000;
// uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000;
// uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000;
// uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000;
// uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_ALL = 0x8000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_ETH = 0x10000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_DAI = 0x20000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_USDC = 0x40000000000000000;
// uint256 internal constant FLAG_DISABLE_MOONISWAP_POOL_TOKEN = 0x80000000000000000;
// }
interface IOneSplit {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) external view returns (uint256 returnAmount, uint256[] memory distribution);
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
external
view
returns (
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) external payable returns (uint256 returnAmount);
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../Initializable.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 {ERC20MinterPauser}.
*
* 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, 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.
*/
function __ERC20_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {
_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 { }
uint256[44] private __gap;
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
import "../../Initializable.sol";
/**
* @dev ERC20 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.
*/
abstract contract ERC20PausableUpgradeSafe is Initializable, ERC20UpgradeSafe, PausableUpgradeSafe {
function __ERC20Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./ERC20.sol";
import "../../Initializable.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeSafe is Initializable, ContextUpgradeSafe, ERC20UpgradeSafe {
function __ERC20Burnable_init() internal initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
uint256[50] private __gap;
}
pragma solidity ^0.6.0;
import "../access/AccessControl.sol";
import "../GSN/Context.sol";
import "../token/ERC20/ERC20.sol";
import "../token/ERC20/ERC20Burnable.sol";
import "../token/ERC20/ERC20Pausable.sol";
import "../Initializable.sol";
/**
* @dev {ERC20} 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 aother accounts
*/
contract ERC20PresetMinterPauserUpgradeSafe is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, ERC20BurnableUpgradeSafe, ERC20PausableUpgradeSafe {
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.
*
* See {ERC20-constructor}.
*/
function initialize(string memory name, string memory symbol) public {
__ERC20PresetMinterPauser_init(name, symbol);
}
function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
__ERC20PresetMinterPauser_init_unchained(name, symbol);
}
function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20UpgradeSafe, ERC20PausableUpgradeSafe) {
super._beforeTokenTransfer(from, to, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/presets/ERC20PresetMinterPauser.sol";
import "./ConfigHelper.sol";
/**
* @title Fidu
* @notice Fidu (symbol: FIDU) is Goldfinch's liquidity token, representing shares
* in the Pool. When you deposit, we mint a corresponding amount of Fidu, and when you withdraw, we
* burn Fidu. The share price of the Pool implicitly represents the "exchange rate" between Fidu
* and USDC (or whatever currencies the Pool may allow withdraws in during the future)
* @author Goldfinch
*/
contract Fidu is ERC20PresetMinterPauserUpgradeSafe {
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
// $1 threshold to handle potential rounding errors, from differing decimals on Fidu and USDC;
uint256 public constant ASSET_LIABILITY_MATCH_THRESHOLD = 1e6;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/*
We are using our own initializer function so we can set the owner by passing it in.
I would override the regular "initializer" function, but I can't because it's not marked
as "virtual" in the parent contract
*/
// solhint-disable-next-line func-name-mixedcase
function __initialize__(
address owner,
string calldata name,
string calldata symbol,
GoldfinchConfig _config
) external initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
config = _config;
_setupRole(MINTER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(MINTER_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) public {
require(canMint(amount), "Cannot mint: it would create an asset/liability mismatch");
// This super call restricts to only the minter in its implementation, so we don't need to do it here.
super.mint(to, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have the MINTER_ROLE
*/
function burnFrom(address from, uint256 amount) public override {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to burn");
require(canBurn(amount), "Cannot burn: it would create an asset/liability mismatch");
_burn(from, amount);
}
// Internal functions
// canMint assumes that the USDC that backs the new shares has already been sent to the Pool
function canMint(uint256 newAmount) internal view returns (bool) {
ISeniorPool seniorPool = config.getSeniorPool();
uint256 liabilities = totalSupply().add(newAmount).mul(seniorPool.sharePrice()).div(fiduMantissa());
uint256 liabilitiesInDollars = fiduToUSDC(liabilities);
uint256 _assets = seniorPool.assets();
if (_assets >= liabilitiesInDollars) {
return true;
} else {
return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD;
}
}
// canBurn assumes that the USDC that backed these shares has already been moved out the Pool
function canBurn(uint256 amountToBurn) internal view returns (bool) {
ISeniorPool seniorPool = config.getSeniorPool();
uint256 liabilities = totalSupply().sub(amountToBurn).mul(seniorPool.sharePrice()).div(fiduMantissa());
uint256 liabilitiesInDollars = fiduToUSDC(liabilities);
uint256 _assets = seniorPool.assets();
if (_assets >= liabilitiesInDollars) {
return true;
} else {
return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD;
}
}
function fiduToUSDC(uint256 amount) internal pure returns (uint256) {
return amount.div(fiduMantissa().div(usdcMantissa()));
}
function fiduMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(18);
}
function usdcMantissa() internal pure returns (uint256) {
return uint256(10)**uint256(6);
}
function updateGoldfinchConfig() external {
require(hasRole(OWNER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to change config");
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "./LeverageRatioStrategy.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ITranchedPool.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
contract FixedLeverageRatioStrategy is LeverageRatioStrategy {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function getLeverageRatio(ITranchedPool pool) public view override returns (uint256) {
return config.getLeverageRatio();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ITranchedPool.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
abstract contract LeverageRatioStrategy is BaseUpgradeablePausable, ISeniorPoolStrategy {
using SafeMath for uint256;
uint256 internal constant LEVERAGE_RATIO_DECIMALS = 1e18;
/**
* @notice Determines how much money to invest in the senior tranche based on what is committed to the junior
* tranche, what is committed to the senior tranche, and a leverage ratio to the junior tranche. Because
* it takes into account what is already committed to the senior tranche, the value returned by this
* function can be used "idempotently" to achieve the investment target amount without exceeding that target.
* @param seniorPool The senior pool to invest from
* @param pool The tranched pool to invest into (as the senior)
* @return The amount of money to invest into the tranched pool's senior tranche, from the senior pool
*/
function invest(ISeniorPool seniorPool, ITranchedPool pool) public view override returns (uint256) {
ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior));
ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
// If junior capital is not yet invested, or pool already locked, then don't invest anything.
if (juniorTranche.lockedUntil == 0 || seniorTranche.lockedUntil > 0) {
return 0;
}
return _invest(pool, juniorTranche, seniorTranche);
}
/**
* @notice A companion of `invest()`: determines how much would be returned by `invest()`, as the
* value to invest into the senior tranche, if the junior tranche were locked and the senior tranche
* were not locked.
* @param seniorPool The senior pool to invest from
* @param pool The tranched pool to invest into (as the senior)
* @return The amount of money to invest into the tranched pool's senior tranche, from the senior pool
*/
function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view override returns (uint256) {
ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior));
ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
return _invest(pool, juniorTranche, seniorTranche);
}
function _invest(
ITranchedPool pool,
ITranchedPool.TrancheInfo memory juniorTranche,
ITranchedPool.TrancheInfo memory seniorTranche
) internal view returns (uint256) {
uint256 juniorCapital = juniorTranche.principalDeposited;
uint256 existingSeniorCapital = seniorTranche.principalDeposited;
uint256 seniorTarget = juniorCapital.mul(getLeverageRatio(pool)).div(LEVERAGE_RATIO_DECIMALS);
if (existingSeniorCapital >= seniorTarget) {
return 0;
}
return seniorTarget.sub(existingSeniorCapital);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "./LeverageRatioStrategy.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ITranchedPool.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
contract DynamicLeverageRatioStrategy is LeverageRatioStrategy {
bytes32 public constant LEVERAGE_RATIO_SETTER_ROLE = keccak256("LEVERAGE_RATIO_SETTER_ROLE");
struct LeverageRatioInfo {
uint256 leverageRatio;
uint256 juniorTrancheLockedUntil;
}
// tranchedPoolAddress => leverageRatioInfo
mapping(address => LeverageRatioInfo) public ratios;
event LeverageRatioUpdated(
address indexed pool,
uint256 leverageRatio,
uint256 juniorTrancheLockedUntil,
bytes32 version
);
function initialize(address owner) public initializer {
require(owner != address(0), "Owner address cannot be empty");
__BaseUpgradeablePausable__init(owner);
_setupRole(LEVERAGE_RATIO_SETTER_ROLE, owner);
_setRoleAdmin(LEVERAGE_RATIO_SETTER_ROLE, OWNER_ROLE);
}
function getLeverageRatio(ITranchedPool pool) public view override returns (uint256) {
LeverageRatioInfo memory ratioInfo = ratios[address(pool)];
ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior));
ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
require(ratioInfo.juniorTrancheLockedUntil > 0, "Leverage ratio has not been set yet.");
if (seniorTranche.lockedUntil > 0) {
// The senior tranche is locked. Coherence check: we expect locking the senior tranche to have
// updated `juniorTranche.lockedUntil` (compared to its value when `setLeverageRatio()` was last
// called successfully).
require(
ratioInfo.juniorTrancheLockedUntil < juniorTranche.lockedUntil,
"Expected junior tranche `lockedUntil` to have been updated."
);
} else {
require(
ratioInfo.juniorTrancheLockedUntil == juniorTranche.lockedUntil,
"Leverage ratio is obsolete. Wait for its recalculation."
);
}
return ratioInfo.leverageRatio;
}
/**
* @notice Updates the leverage ratio for the specified tranched pool. The combination of the
* `juniorTranchedLockedUntil` param and the `version` param in the event emitted by this
* function are intended to enable an outside observer to verify the computation of the leverage
* ratio set by calls of this function.
* @param pool The tranched pool whose leverage ratio to update.
* @param leverageRatio The leverage ratio value to set for the tranched pool.
* @param juniorTrancheLockedUntil The `lockedUntil` timestamp, of the tranched pool's
* junior tranche, to which this calculation of `leverageRatio` corresponds, i.e. the
* value of the `lockedUntil` timestamp of the JuniorCapitalLocked event which the caller
* is calling this function in response to having observed. By providing this timestamp
* (plus an assumption that we can trust the caller to report this value accurately),
* the caller enables this function to enforce that a leverage ratio that is obsolete in
* the sense of having been calculated for an obsolete `lockedUntil` timestamp cannot be set.
* @param version An arbitrary identifier included in the LeverageRatioUpdated event emitted
* by this function, enabling the caller to describe how it calculated `leverageRatio`. Using
* the bytes32 type accommodates using git commit hashes (both the current SHA1 hashes, which
* require 20 bytes; and the future SHA256 hashes, which require 32 bytes) for this value.
*/
function setLeverageRatio(
ITranchedPool pool,
uint256 leverageRatio,
uint256 juniorTrancheLockedUntil,
bytes32 version
) public onlySetterRole {
ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior));
ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior));
// NOTE: We allow a `leverageRatio` of 0.
require(
leverageRatio <= 10 * LEVERAGE_RATIO_DECIMALS,
"Leverage ratio must not exceed 10 (adjusted for decimals)."
);
require(juniorTranche.lockedUntil > 0, "Cannot set leverage ratio if junior tranche is not locked.");
require(seniorTranche.lockedUntil == 0, "Cannot set leverage ratio if senior tranche is locked.");
require(juniorTrancheLockedUntil == juniorTranche.lockedUntil, "Invalid `juniorTrancheLockedUntil` timestamp.");
ratios[address(pool)] = LeverageRatioInfo({
leverageRatio: leverageRatio,
juniorTrancheLockedUntil: juniorTrancheLockedUntil
});
emit LeverageRatioUpdated(address(pool), leverageRatio, juniorTrancheLockedUntil, version);
}
modifier onlySetterRole() {
require(
hasRole(LEVERAGE_RATIO_SETTER_ROLE, _msgSender()),
"Must have leverage-ratio setter role to perform this action"
);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.5 <0.8.0;
import "../token/ERC20/ERC20.sol";
import "./IERC20Permit.sol";
import "../cryptography/ECDSA.sol";
import "../utils/Counters.sol";
import "./EIP712.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping (address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) internal EIP712(name, "1") {
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_nonces[owner].current(),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_nonces[owner].increment();
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
}
// 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 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 {
/**
* @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) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* 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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. 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;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
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 {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) internal {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = _getChainId();
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
if (_getChainId() == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
_getChainId(),
address(this)
)
);
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
}
// 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.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;
/**
* @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;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC20 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.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./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 () internal {
_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.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";
/**
* @title GFI
* @notice GFI is Goldfinch's governance token.
* @author Goldfinch
*/
contract GFI is Context, AccessControl, ERC20Burnable, ERC20Pausable {
using SafeMath for uint256;
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/// The maximum number of tokens that can be minted
uint256 public cap;
event CapUpdated(address indexed who, uint256 cap);
constructor(
address owner,
string memory name,
string memory symbol,
uint256 initialCap
) public ERC20(name, symbol) {
cap = initialCap;
_setupRole(MINTER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(MINTER_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/**
* @notice create and send tokens to a specified address
* @dev this function will fail if the caller attempts to mint over the current cap
*/
function mint(address account, uint256 amount) public onlyMinter whenNotPaused {
require(mintingAmountIsWithinCap(amount), "Cannot mint more than cap");
_mint(account, amount);
}
/**
* @notice sets the maximum number of tokens that can be minted
* @dev the cap must be greater than the current total supply
*/
function setCap(uint256 _cap) external onlyOwner {
require(_cap >= totalSupply(), "Cannot decrease the cap below existing supply");
cap = _cap;
emit CapUpdated(_msgSender(), cap);
}
function mintingAmountIsWithinCap(uint256 amount) internal returns (bool) {
return totalSupply().add(amount) <= cap;
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() external onlyPauser {
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() external onlyPauser {
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
modifier onlyOwner() {
require(hasRole(OWNER_ROLE, _msgSender()), "Must be owner");
_;
}
modifier onlyMinter() {
require(hasRole(MINTER_ROLE, _msgSender()), "Must be minter");
_;
}
modifier onlyPauser() {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must be pauser");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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 {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @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 {_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) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_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 {
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 {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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;
// 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];
}
// 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);
}
// 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))));
}
// 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));
}
}
// 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:MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
// Taken from https://github.com/opengsn/forwarder/blob/master/contracts/Forwarder.sol and adapted to work locally
// Main change is removing interface inheritance and adding a some debugging niceities
contract TestForwarder {
using ECDSA for bytes32;
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
}
string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data";
string public constant EIP712_DOMAIN_TYPE =
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"; // solhint-disable-line max-line-length
mapping(bytes32 => bool) public typeHashes;
mapping(bytes32 => bool) public domains;
// Nonces of senders, used to prevent replay attacks
mapping(address => uint256) private nonces;
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
function getNonce(address from) public view returns (uint256) {
return nonces[from];
}
constructor() public {
string memory requestType = string(abi.encodePacked("ForwardRequest(", GENERIC_PARAMS, ")"));
registerRequestTypeInternal(requestType);
}
function verify(
ForwardRequest memory req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig
) external view {
_verifyNonce(req);
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
}
function execute(
ForwardRequest memory req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig
) external payable returns (bool success, bytes memory ret) {
_verifyNonce(req);
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
_updateNonce(req);
// solhint-disable-next-line avoid-low-level-calls
(success, ret) = req.to.call{gas: req.gas, value: req.value}(abi.encodePacked(req.data, req.from));
// Added by Goldfinch for debugging
if (!success) {
require(success, string(ret));
}
if (address(this).balance > 0) {
//can't fail: req.from signed (off-chain) the request, so it must be an EOA...
payable(req.from).transfer(address(this).balance);
}
return (success, ret);
}
function _verifyNonce(ForwardRequest memory req) internal view {
require(nonces[req.from] == req.nonce, "nonce mismatch");
}
function _updateNonce(ForwardRequest memory req) internal {
nonces[req.from]++;
}
function registerRequestType(string calldata typeName, string calldata typeSuffix) external {
for (uint256 i = 0; i < bytes(typeName).length; i++) {
bytes1 c = bytes(typeName)[i];
require(c != "(" && c != ")", "invalid typename");
}
string memory requestType = string(abi.encodePacked(typeName, "(", GENERIC_PARAMS, ",", typeSuffix));
registerRequestTypeInternal(requestType);
}
function registerDomainSeparator(string calldata name, string calldata version) external {
uint256 chainId;
/* solhint-disable-next-line no-inline-assembly */
assembly {
chainId := chainid()
}
bytes memory domainValue = abi.encode(
keccak256(bytes(EIP712_DOMAIN_TYPE)),
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
address(this)
);
bytes32 domainHash = keccak256(domainValue);
domains[domainHash] = true;
emit DomainRegistered(domainHash, domainValue);
}
function registerRequestTypeInternal(string memory requestType) internal {
bytes32 requestTypehash = keccak256(bytes(requestType));
typeHashes[requestTypehash] = true;
emit RequestTypeRegistered(requestTypehash, requestType);
}
event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue);
event RequestTypeRegistered(bytes32 indexed typeHash, string typeStr);
function _verifySig(
ForwardRequest memory req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes memory suffixData,
bytes memory sig
) internal view {
require(domains[domainSeparator], "unregistered domain separator");
require(typeHashes[requestTypeHash], "unregistered request typehash");
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, keccak256(_getEncoded(req, requestTypeHash, suffixData)))
);
require(digest.recover(sig) == req.from, "signature mismatch");
}
function _getEncoded(
ForwardRequest memory req,
bytes32 requestTypeHash,
bytes memory suffixData
) public pure returns (bytes memory) {
return
abi.encodePacked(
requestTypeHash,
abi.encode(req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)),
suffixData
);
}
}
// contracts/GLDToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/drafts/ERC20Permit.sol";
contract TestERC20 is ERC20("USD Coin", "USDC"), ERC20Permit("USD Coin") {
constructor(uint256 initialSupply, uint8 decimals) public {
_setupDecimals(decimals);
_mint(msg.sender, initialSupply);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../external/ERC721PresetMinterPauserAutoId.sol";
import "./GoldfinchConfig.sol";
import "./ConfigHelper.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IPoolTokens.sol";
/**
* @title PoolTokens
* @notice PoolTokens is an ERC721 compliant contract, which can represent
* junior tranche or senior tranche shares of any of the borrower pools.
* @author Goldfinch
*/
contract PoolTokens is IPoolTokens, ERC721PresetMinterPauserAutoIdUpgradeSafe {
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
struct PoolInfo {
uint256 totalMinted;
uint256 totalPrincipalRedeemed;
bool created;
}
// tokenId => tokenInfo
mapping(uint256 => TokenInfo) public tokens;
// poolAddress => poolInfo
mapping(address => PoolInfo) public pools;
event TokenMinted(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 amount,
uint256 tranche
);
event TokenRedeemed(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed,
uint256 tranche
);
event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/*
We are using our own initializer function so that OZ doesn't automatically
set owner as msg.sender. Also, it lets us set our config contract
*/
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) external initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC165_init_unchained();
// This is setting name and symbol of the NFT's
__ERC721_init_unchained("Goldfinch V2 Pool Tokens", "GFI-V2-PT");
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
config = _config;
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/**
* @notice Called by pool to create a debt position in a particular tranche and amount
* @param params Struct containing the tranche and the amount
* @param to The address that should own the position
* @return tokenId The token ID (auto-incrementing integer across all pools)
*/
function mint(MintParams calldata params, address to)
external
virtual
override
onlyPool
whenNotPaused
returns (uint256 tokenId)
{
address poolAddress = _msgSender();
tokenId = createToken(params, poolAddress);
_mint(to, tokenId);
config.getBackerRewards().setPoolTokenAccRewardsPerPrincipalDollarAtMint(_msgSender(), tokenId);
emit TokenMinted(to, poolAddress, tokenId, params.principalAmount, params.tranche);
return tokenId;
}
/**
* @notice Updates a token to reflect the principal and interest amounts that have been redeemed.
* @param tokenId The token id to update (must be owned by the pool calling this function)
* @param principalRedeemed The incremental amount of principal redeemed (cannot be more than principal deposited)
* @param interestRedeemed The incremental amount of interest redeemed
*/
function redeem(
uint256 tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed
) external virtual override onlyPool whenNotPaused {
TokenInfo storage token = tokens[tokenId];
address poolAddr = token.pool;
require(token.pool != address(0), "Invalid tokenId");
require(_msgSender() == poolAddr, "Only the token's pool can redeem");
PoolInfo storage pool = pools[poolAddr];
pool.totalPrincipalRedeemed = pool.totalPrincipalRedeemed.add(principalRedeemed);
require(pool.totalPrincipalRedeemed <= pool.totalMinted, "Cannot redeem more than we minted");
token.principalRedeemed = token.principalRedeemed.add(principalRedeemed);
require(
token.principalRedeemed <= token.principalAmount,
"Cannot redeem more than principal-deposited amount for token"
);
token.interestRedeemed = token.interestRedeemed.add(interestRedeemed);
emit TokenRedeemed(ownerOf(tokenId), poolAddr, tokenId, principalRedeemed, interestRedeemed, token.tranche);
}
/**
* @dev Burns a specific ERC721 token, and removes the data from our mappings
* @param tokenId uint256 id of the ERC721 token to be burned.
*/
function burn(uint256 tokenId) external virtual override whenNotPaused {
TokenInfo memory token = _getTokenInfo(tokenId);
bool canBurn = _isApprovedOrOwner(_msgSender(), tokenId);
bool fromTokenPool = _validPool(_msgSender()) && token.pool == _msgSender();
address owner = ownerOf(tokenId);
require(canBurn || fromTokenPool, "ERC721Burnable: caller cannot burn this token");
require(token.principalRedeemed == token.principalAmount, "Can only burn fully redeemed tokens");
destroyAndBurn(tokenId);
emit TokenBurned(owner, token.pool, tokenId);
}
function getTokenInfo(uint256 tokenId) external view virtual override returns (TokenInfo memory) {
return _getTokenInfo(tokenId);
}
/**
* @notice Called by the GoldfinchFactory to register the pool as a valid pool. Only valid pools can mint/redeem
* tokens
* @param newPool The address of the newly created pool
*/
function onPoolCreated(address newPool) external override onlyGoldfinchFactory {
pools[newPool].created = true;
}
/**
* @notice Returns a boolean representing whether the spender is the owner or the approved spender of the token
* @param spender The address to check
* @param tokenId The token id to check for
* @return True if approved to redeem/transfer/burn the token, false if not
*/
function isApprovedOrOwner(address spender, uint256 tokenId) external view override returns (bool) {
return _isApprovedOrOwner(spender, tokenId);
}
function validPool(address sender) public view virtual override returns (bool) {
return _validPool(sender);
}
function createToken(MintParams calldata params, address poolAddress) internal returns (uint256 tokenId) {
PoolInfo storage pool = pools[poolAddress];
_tokenIdTracker.increment();
tokenId = _tokenIdTracker.current();
tokens[tokenId] = TokenInfo({
pool: poolAddress,
tranche: params.tranche,
principalAmount: params.principalAmount,
principalRedeemed: 0,
interestRedeemed: 0
});
pool.totalMinted = pool.totalMinted.add(params.principalAmount);
return tokenId;
}
function destroyAndBurn(uint256 tokenId) internal {
delete tokens[tokenId];
_burn(tokenId);
}
function _validPool(address poolAddress) internal view virtual returns (bool) {
return pools[poolAddress].created;
}
function _getTokenInfo(uint256 tokenId) internal view returns (TokenInfo memory) {
return tokens[tokenId];
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyGoldfinchFactory() {
require(_msgSender() == config.goldfinchFactoryAddress(), "Only Goldfinch factory is allowed");
_;
}
modifier onlyPool() {
require(_validPool(_msgSender()), "Invalid pool!");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/PoolTokens.sol";
contract TestPoolTokens is PoolTokens {
bool public disablePoolValidation;
address payable public sender;
// solhint-disable-next-line modifiers/ensure-modifiers
function _disablePoolValidation(bool shouldDisable) public {
disablePoolValidation = shouldDisable;
}
// solhint-disable-next-line modifiers/ensure-modifiers
function _setSender(address payable _sender) public {
sender = _sender;
}
function _validPool(address _sender) internal view override returns (bool) {
if (disablePoolValidation) {
return true;
} else {
return super._validPool(_sender);
}
}
function _msgSender() internal view override returns (address payable) {
if (sender != address(0)) {
return sender;
} else {
return super._msgSender();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IV2CreditLine.sol";
import "./IV1CreditLine.sol";
import "./ITranchedPool.sol";
abstract contract IMigratedTranchedPool is ITranchedPool {
function migrateCreditLineToV2(
IV1CreditLine clToMigrate,
uint256 termEndTime,
uint256 nextDueTime,
uint256 interestAccruedAsOf,
uint256 lastFullPaymentTime,
uint256 totalInterestPaid
) external virtual returns (IV2CreditLine);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IV1CreditLine {
address public borrower;
address public underwriter;
uint256 public limit;
uint256 public interestApr;
uint256 public paymentPeriodInDays;
uint256 public termInDays;
uint256 public lateFeeApr;
uint256 public balance;
uint256 public interestOwed;
uint256 public principalOwed;
uint256 public termEndBlock;
uint256 public nextDueBlock;
uint256 public interestAccruedAsOfBlock;
uint256 public writedownAmount;
uint256 public lastFullPaymentBlock;
function setLimit(uint256 newAmount) external virtual;
function setBalance(uint256 newBalance) external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./TranchedPool.sol";
import "../../interfaces/IV1CreditLine.sol";
import "../../interfaces/IMigratedTranchedPool.sol";
contract MigratedTranchedPool is TranchedPool, IMigratedTranchedPool {
bool public migrated;
function migrateCreditLineToV2(
IV1CreditLine clToMigrate,
uint256 termEndTime,
uint256 nextDueTime,
uint256 interestAccruedAsOf,
uint256 lastFullPaymentTime,
uint256 totalInterestPaid
) external override returns (IV2CreditLine) {
require(msg.sender == config.creditDeskAddress(), "Only credit desk can call this");
require(!migrated, "Already migrated");
// Set accounting state vars.
IV2CreditLine newCl = creditLine;
newCl.setBalance(clToMigrate.balance());
newCl.setInterestOwed(clToMigrate.interestOwed());
newCl.setPrincipalOwed(clToMigrate.principalOwed());
newCl.setTermEndTime(termEndTime);
newCl.setNextDueTime(nextDueTime);
newCl.setInterestAccruedAsOf(interestAccruedAsOf);
newCl.setLastFullPaymentTime(lastFullPaymentTime);
newCl.setTotalInterestAccrued(totalInterestPaid.add(clToMigrate.interestOwed()));
migrateDeposits(clToMigrate, totalInterestPaid);
migrated = true;
return newCl;
}
function migrateDeposits(IV1CreditLine clToMigrate, uint256 totalInterestPaid) internal {
// Mint junior tokens to the SeniorPool, equal to current cl balance;
require(!locked(), "Pool has been locked");
// Hardcode to always get the JuniorTranche, since the migration case is when
// the senior pool took the entire investment. Which we're expressing as the junior tranche
uint256 tranche = uint256(ITranchedPool.Tranches.Junior);
TrancheInfo storage trancheInfo = getTrancheInfo(tranche);
require(trancheInfo.lockedUntil == 0, "Tranche has been locked");
trancheInfo.principalDeposited = clToMigrate.limit();
IPoolTokens.MintParams memory params = IPoolTokens.MintParams({
tranche: tranche,
principalAmount: trancheInfo.principalDeposited
});
IPoolTokens poolTokens = config.getPoolTokens();
uint256 tokenId = poolTokens.mint(params, config.seniorPoolAddress());
uint256 balancePaid = creditLine.limit().sub(creditLine.balance());
// Account for the implicit redemptions already made by the Legacy Pool
_lockJuniorCapital(poolSlices.length - 1);
_lockPool();
PoolSlice storage currentSlice = poolSlices[poolSlices.length - 1];
currentSlice.juniorTranche.lockedUntil = block.timestamp - 1;
poolTokens.redeem(tokenId, balancePaid, totalInterestPaid);
// Simulate the drawdown
currentSlice.juniorTranche.principalSharePrice = 0;
currentSlice.seniorTranche.principalSharePrice = 0;
// Set junior's sharePrice correctly
currentSlice.juniorTranche.applyByAmount(totalInterestPaid, balancePaid, totalInterestPaid, balancePaid);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "./Accountant.sol";
import "./CreditLine.sol";
import "./GoldfinchFactory.sol";
import "../../interfaces/IV1CreditLine.sol";
import "../../interfaces/IMigratedTranchedPool.sol";
/**
* @title Goldfinch's CreditDesk contract
* @notice Main entry point for borrowers and underwriters.
* Handles key logic for creating CreditLine's, borrowing money, repayment, etc.
* @author Goldfinch
*/
contract CreditDesk is BaseUpgradeablePausable, ICreditDesk {
uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
struct Underwriter {
uint256 governanceLimit;
address[] creditLines;
}
struct Borrower {
address[] creditLines;
}
event PaymentApplied(
address indexed payer,
address indexed creditLine,
uint256 interestAmount,
uint256 principalAmount,
uint256 remainingAmount
);
event PaymentCollected(address indexed payer, address indexed creditLine, uint256 paymentAmount);
event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount);
event CreditLineCreated(address indexed borrower, address indexed creditLine);
event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit);
mapping(address => Underwriter) public underwriters;
mapping(address => Borrower) private borrowers;
mapping(address => address) private creditLines;
/**
* @notice Run only once, on initialization
* @param owner The address of who should have the "OWNER_ROLE" of this contract
* @param _config The address of the GoldfinchConfig contract
*/
function initialize(address owner, GoldfinchConfig _config) public initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = _config;
}
/**
* @notice Sets a particular underwriter's limit of how much credit the DAO will allow them to "create"
* @param underwriterAddress The address of the underwriter for whom the limit shall change
* @param limit What the new limit will be set to
* Requirements:
*
* - the caller must have the `OWNER_ROLE`.
*/
function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit)
external
override
onlyAdmin
whenNotPaused
{
require(withinMaxUnderwriterLimit(limit), "This limit is greater than the max allowed by the protocol");
underwriters[underwriterAddress].governanceLimit = limit;
emit GovernanceUpdatedUnderwriterLimit(underwriterAddress, limit);
}
/**
* @notice Allows a borrower to drawdown on their creditline.
* `amount` USDC is sent to the borrower, and the credit line accounting is updated.
* @param creditLineAddress The creditline from which they would like to drawdown
* @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown
*
* Requirements:
*
* - the caller must be the borrower on the creditLine
*/
function drawdown(address creditLineAddress, uint256 amount)
external
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
CreditLine cl = CreditLine(creditLineAddress);
Borrower storage borrower = borrowers[msg.sender];
require(borrower.creditLines.length > 0, "No credit lines exist for this borrower");
require(amount > 0, "Must drawdown more than zero");
require(cl.borrower() == msg.sender, "You are not the borrower of this credit line");
require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");
uint256 unappliedBalance = getUSDCBalance(creditLineAddress);
require(
withinCreditLimit(amount, unappliedBalance, cl),
"The borrower does not have enough credit limit for this drawdown"
);
uint256 balance = cl.balance();
if (balance == 0) {
cl.setInterestAccruedAsOf(currentTime());
cl.setLastFullPaymentTime(currentTime());
}
IPool pool = config.getPool();
// If there is any balance on the creditline that has not been applied yet, then use that first before
// drawing down from the pool. This is to support cases where the borrower partially pays back the
// principal before the due date, but then decides to drawdown again
uint256 amountToTransferFromCL;
if (unappliedBalance > 0) {
if (amount > unappliedBalance) {
amountToTransferFromCL = unappliedBalance;
amount = amount.sub(unappliedBalance);
} else {
amountToTransferFromCL = amount;
amount = 0;
}
bool success = pool.transferFrom(creditLineAddress, msg.sender, amountToTransferFromCL);
require(success, "Failed to drawdown");
}
(uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, currentTime());
balance = balance.add(amount);
updateCreditLineAccounting(cl, balance, interestOwed, principalOwed);
// Must put this after we update the credit line accounting, so we're using the latest
// interestOwed
require(!isLate(cl, currentTime()), "Cannot drawdown when payments are past due");
emit DrawdownMade(msg.sender, address(cl), amount.add(amountToTransferFromCL));
if (amount > 0) {
bool success = pool.drawdown(msg.sender, amount);
require(success, "Failed to drawdown");
}
}
/**
* @notice Allows a borrower to repay their loan. Payment is *collected* immediately (by sending it to
* the individual CreditLine), but it is not *applied* unless it is after the nextDueTime, or until we assess
* the credit line (ie. payment period end).
* Any amounts over the minimum payment will be applied to outstanding principal (reducing the effective
* interest rate). If there is still any left over, it will remain in the USDC Balance
* of the CreditLine, which is held distinct from the Pool amounts, and can not be withdrawn by LP's.
* @param creditLineAddress The credit line to be paid back
* @param amount The amount, in USDC atomic units, that a borrower wishes to pay
*/
function pay(address creditLineAddress, uint256 amount)
external
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
require(amount > 0, "Must pay more than zero");
CreditLine cl = CreditLine(creditLineAddress);
collectPayment(cl, amount);
assessCreditLine(creditLineAddress);
}
/**
* @notice Assesses a particular creditLine. This will apply payments, which will update accounting and
* distribute gains or losses back to the pool accordingly. This function is idempotent, and anyone
* is allowed to call it.
* @param creditLineAddress The creditline that should be assessed.
*/
function assessCreditLine(address creditLineAddress)
public
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
CreditLine cl = CreditLine(creditLineAddress);
// Do not assess until a full period has elapsed or past due
require(cl.balance() > 0, "Must have balance to assess credit line");
// Don't assess credit lines early!
if (currentTime() < cl.nextDueTime() && !isLate(cl, currentTime())) {
return;
}
uint256 timeToAssess = calculateNextDueTime(cl);
cl.setNextDueTime(timeToAssess);
// We always want to assess for the most recently *past* nextDueTime.
// So if the recalculation above sets the nextDueTime into the future,
// then ensure we pass in the one just before this.
if (timeToAssess > currentTime()) {
uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY);
timeToAssess = timeToAssess.sub(secondsPerPeriod);
}
_applyPayment(cl, getUSDCBalance(address(cl)), timeToAssess);
}
function applyPayment(address creditLineAddress, uint256 amount)
external
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
CreditLine cl = CreditLine(creditLineAddress);
require(cl.borrower() == msg.sender, "You do not belong to this credit line");
_applyPayment(cl, amount, currentTime());
}
function migrateV1CreditLine(
address _clToMigrate,
address borrower,
uint256 termEndTime,
uint256 nextDueTime,
uint256 interestAccruedAsOf,
uint256 lastFullPaymentTime,
uint256 totalInterestPaid
) public onlyAdmin returns (address, address) {
IV1CreditLine clToMigrate = IV1CreditLine(_clToMigrate);
uint256 originalBalance = clToMigrate.balance();
require(clToMigrate.limit() > 0, "Can't migrate empty credit line");
require(originalBalance > 0, "Can't migrate credit line that's currently paid off");
// Ensure it is a v1 creditline by calling a function that only exists on v1
require(clToMigrate.nextDueBlock() > 0, "Invalid creditline");
if (borrower == address(0)) {
borrower = clToMigrate.borrower();
}
// We're migrating from 1e8 decimal precision of interest rates to 1e18
// So multiply the legacy rates by 1e10 to normalize them.
uint256 interestMigrationFactor = 1e10;
uint256[] memory allowedUIDTypes;
address pool = getGoldfinchFactory().createMigratedPool(
borrower,
20, // junior fee percent
clToMigrate.limit(),
clToMigrate.interestApr().mul(interestMigrationFactor),
clToMigrate.paymentPeriodInDays(),
clToMigrate.termInDays(),
clToMigrate.lateFeeApr(),
0,
0,
allowedUIDTypes
);
IV2CreditLine newCl = IMigratedTranchedPool(pool).migrateCreditLineToV2(
clToMigrate,
termEndTime,
nextDueTime,
interestAccruedAsOf,
lastFullPaymentTime,
totalInterestPaid
);
// Close out the original credit line
clToMigrate.setLimit(0);
clToMigrate.setBalance(0);
// Some sanity checks on the migration
require(newCl.balance() == originalBalance, "Balance did not migrate properly");
require(newCl.interestAccruedAsOf() == interestAccruedAsOf, "Interest accrued as of did not migrate properly");
return (address(newCl), pool);
}
/**
* @notice Simple getter for the creditlines of a given underwriter
* @param underwriterAddress The underwriter address you would like to see the credit lines of.
*/
function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) {
return underwriters[underwriterAddress].creditLines;
}
/**
* @notice Simple getter for the creditlines of a given borrower
* @param borrowerAddress The borrower address you would like to see the credit lines of.
*/
function getBorrowerCreditLines(address borrowerAddress) public view returns (address[] memory) {
return borrowers[borrowerAddress].creditLines;
}
/**
* @notice This function is only meant to be used by frontends. It returns the total
* payment due for a given creditLine as of the provided timestamp. Returns 0 if no
* payment is due (e.g. asOf is before the nextDueTime)
* @param creditLineAddress The creditLine to calculate the payment for
* @param asOf The timestamp to use for the payment calculation, if it is set to 0, uses the current time
*/
function getNextPaymentAmount(address creditLineAddress, uint256 asOf)
external
view
override
onlyValidCreditLine(creditLineAddress)
returns (uint256)
{
if (asOf == 0) {
asOf = currentTime();
}
CreditLine cl = CreditLine(creditLineAddress);
if (asOf < cl.nextDueTime() && !isLate(cl, currentTime())) {
return 0;
}
(uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
cl,
asOf,
config.getLatenessGracePeriodInDays()
);
return cl.interestOwed().add(interestAccrued).add(cl.principalOwed().add(principalAccrued));
}
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
}
/*
* Internal Functions
*/
/**
* @notice Collects `amount` of payment for a given credit line. This sends money from the payer to the credit line.
* Note that payment is not *applied* when calling this function. Only collected (ie. held) for later application.
* @param cl The CreditLine the payment will be collected for.
* @param amount The amount, in USDC atomic units, to be collected
*/
function collectPayment(CreditLine cl, uint256 amount) internal {
require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");
emit PaymentCollected(msg.sender, address(cl), amount);
bool success = config.getPool().transferFrom(msg.sender, address(cl), amount);
require(success, "Failed to collect payment");
}
/**
* @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool.
* It also updates all the accounting variables. Note that interest is always paid back first, then principal.
* Any extra after paying the minimum will go towards existing principal (reducing the
* effective interest rate). Any extra after the full loan has been paid off will remain in the
* USDC Balance of the creditLine, where it will be automatically used for the next drawdown.
* @param cl The CreditLine the payment will be collected for.
* @param amount The amount, in USDC atomic units, to be applied
* @param timestamp The timestamp on which accrual calculations should be based. This allows us
* to be precise when we assess a Credit Line
*/
function _applyPayment(
CreditLine cl,
uint256 amount,
uint256 timestamp
) internal {
(uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = handlePayment(
cl,
amount,
timestamp
);
IPool pool = config.getPool();
if (interestPayment > 0 || principalPayment > 0) {
emit PaymentApplied(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining);
pool.collectInterestAndPrincipal(address(cl), interestPayment, principalPayment);
}
}
function handlePayment(
CreditLine cl,
uint256 paymentAmount,
uint256 timestamp
)
internal
returns (
uint256,
uint256,
uint256
)
{
(uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, timestamp);
Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(
paymentAmount,
cl.balance(),
interestOwed,
principalOwed
);
uint256 newBalance = cl.balance().sub(pa.principalPayment);
// Apply any additional payment towards the balance
newBalance = newBalance.sub(pa.additionalBalancePayment);
uint256 totalPrincipalPayment = cl.balance().sub(newBalance);
uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment);
updateCreditLineAccounting(
cl,
newBalance,
interestOwed.sub(pa.interestPayment),
principalOwed.sub(pa.principalPayment)
);
assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount);
return (paymentRemaining, pa.interestPayment, totalPrincipalPayment);
}
function isLate(CreditLine cl, uint256 timestamp) internal view returns (bool) {
uint256 secondsElapsedSinceFullPayment = timestamp.sub(cl.lastFullPaymentTime());
return secondsElapsedSinceFullPayment > cl.paymentPeriodInDays().mul(SECONDS_PER_DAY);
}
function getGoldfinchFactory() internal view returns (GoldfinchFactory) {
return GoldfinchFactory(config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory)));
}
function updateAndGetInterestAndPrincipalOwedAsOf(CreditLine cl, uint256 timestamp)
internal
returns (uint256, uint256)
{
(uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(
cl,
timestamp,
config.getLatenessGracePeriodInDays()
);
if (interestAccrued > 0) {
// If we've accrued any interest, update interestAccruedAsOf to the time that we've
// calculated interest for. If we've not accrued any interest, then we keep the old value so the next
// time the entire period is taken into account.
cl.setInterestAccruedAsOf(timestamp);
}
return (cl.interestOwed().add(interestAccrued), cl.principalOwed().add(principalAccrued));
}
function withinCreditLimit(
uint256 amount,
uint256 unappliedBalance,
CreditLine cl
) internal view returns (bool) {
return cl.balance().add(amount).sub(unappliedBalance) <= cl.limit();
}
function withinTransactionLimit(uint256 amount) internal view returns (bool) {
return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit));
}
function calculateNewTermEndTime(CreditLine cl, uint256 balance) internal view returns (uint256) {
// If there's no balance, there's no loan, so there's no term end time
if (balance == 0) {
return 0;
}
// Don't allow any weird bugs where we add to your current end time. This
// function should only be used on new credit lines, when we are setting them up
if (cl.termEndTime() != 0) {
return cl.termEndTime();
}
return currentTime().add(SECONDS_PER_DAY.mul(cl.termInDays()));
}
function calculateNextDueTime(CreditLine cl) internal view returns (uint256) {
uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY);
uint256 balance = cl.balance();
uint256 nextDueTime = cl.nextDueTime();
uint256 curTimestamp = currentTime();
// You must have just done your first drawdown
if (nextDueTime == 0 && balance > 0) {
return curTimestamp.add(secondsPerPeriod);
}
// Active loan that has entered a new period, so return the *next* nextDueTime.
// But never return something after the termEndTime
if (balance > 0 && curTimestamp >= nextDueTime) {
uint256 secondsToAdvance = (curTimestamp.sub(nextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod);
nextDueTime = nextDueTime.add(secondsToAdvance);
return Math.min(nextDueTime, cl.termEndTime());
}
// Your paid off, or have not taken out a loan yet, so no next due time.
if (balance == 0 && nextDueTime != 0) {
return 0;
}
// Active loan in current period, where we've already set the nextDueTime correctly, so should not change.
if (balance > 0 && curTimestamp < nextDueTime) {
return nextDueTime;
}
revert("Error: could not calculate next due time.");
}
function currentTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function underwriterCanCreateThisCreditLine(uint256 newAmount, Underwriter storage underwriter)
internal
view
returns (bool)
{
uint256 underwriterLimit = underwriter.governanceLimit;
require(underwriterLimit != 0, "underwriter does not have governance limit");
uint256 creditCurrentlyExtended = getCreditCurrentlyExtended(underwriter);
uint256 totalToBeExtended = creditCurrentlyExtended.add(newAmount);
return totalToBeExtended <= underwriterLimit;
}
function withinMaxUnderwriterLimit(uint256 amount) internal view returns (bool) {
return amount <= config.getNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit));
}
function getCreditCurrentlyExtended(Underwriter storage underwriter) internal view returns (uint256) {
uint256 creditExtended;
uint256 length = underwriter.creditLines.length;
for (uint256 i = 0; i < length; i++) {
CreditLine cl = CreditLine(underwriter.creditLines[i]);
creditExtended = creditExtended.add(cl.limit());
}
return creditExtended;
}
function updateCreditLineAccounting(
CreditLine cl,
uint256 balance,
uint256 interestOwed,
uint256 principalOwed
) internal nonReentrant {
// subtract cl from total loans outstanding
totalLoansOutstanding = totalLoansOutstanding.sub(cl.balance());
cl.setBalance(balance);
cl.setInterestOwed(interestOwed);
cl.setPrincipalOwed(principalOwed);
// This resets lastFullPaymentTime. These conditions assure that they have
// indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown)
uint256 nextDueTime = cl.nextDueTime();
if (interestOwed == 0 && nextDueTime != 0) {
// If interest was fully paid off, then set the last full payment as the previous due time
uint256 mostRecentLastDueTime;
if (currentTime() < nextDueTime) {
uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY);
mostRecentLastDueTime = nextDueTime.sub(secondsPerPeriod);
} else {
mostRecentLastDueTime = nextDueTime;
}
cl.setLastFullPaymentTime(mostRecentLastDueTime);
}
// Add new amount back to total loans outstanding
totalLoansOutstanding = totalLoansOutstanding.add(balance);
cl.setTermEndTime(calculateNewTermEndTime(cl, balance)); // pass in balance as a gas optimization
cl.setNextDueTime(calculateNextDueTime(cl));
}
function getUSDCBalance(address _address) internal view returns (uint256) {
return config.getUSDC().balanceOf(_address);
}
modifier onlyValidCreditLine(address clAddress) {
require(creditLines[clAddress] != address(0), "Unknown credit line");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/CreditDesk.sol";
contract TestCreditDesk is CreditDesk {
// solhint-disable-next-line modifiers/ensure-modifiers
function _setTotalLoansOutstanding(uint256 amount) public {
totalLoansOutstanding = amount;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../core/BaseUpgradeablePausable.sol";
import "../core/ConfigHelper.sol";
import "../core/CreditLine.sol";
import "../core/GoldfinchConfig.sol";
import "../../interfaces/IMigrate.sol";
/**
* @title V2 Migrator Contract
* @notice This is a one-time use contract solely for the purpose of migrating from our V1
* to our V2 architecture. It will be temporarily granted authority from the Goldfinch governance,
* and then revokes it's own authority and transfers it back to governance.
* @author Goldfinch
*/
contract V2Migrator is BaseUpgradeablePausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE");
using SafeMath for uint256;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
mapping(address => address) public borrowerContracts;
event CreditLineMigrated(address indexed owner, address indexed clToMigrate, address newCl, address tranchedPool);
function initialize(address owner, address _config) external initializer {
require(owner != address(0) && _config != address(0), "Owner and config addresses cannot be empty");
__BaseUpgradeablePausable__init(owner);
config = GoldfinchConfig(_config);
}
function migratePhase1(GoldfinchConfig newConfig) external onlyAdmin {
pauseEverything();
migrateToNewConfig(newConfig);
migrateToSeniorPool(newConfig);
}
function migrateCreditLines(
GoldfinchConfig newConfig,
address[][] calldata creditLinesToMigrate,
uint256[][] calldata migrationData
) external onlyAdmin {
IMigrate creditDesk = IMigrate(newConfig.creditDeskAddress());
IGoldfinchFactory factory = newConfig.getGoldfinchFactory();
for (uint256 i = 0; i < creditLinesToMigrate.length; i++) {
address[] calldata clData = creditLinesToMigrate[i];
uint256[] calldata data = migrationData[i];
address clAddress = clData[0];
address owner = clData[1];
address borrowerContract = borrowerContracts[owner];
if (borrowerContract == address(0)) {
borrowerContract = factory.createBorrower(owner);
borrowerContracts[owner] = borrowerContract;
}
(address newCl, address pool) = creditDesk.migrateV1CreditLine(
clAddress,
borrowerContract,
data[0],
data[1],
data[2],
data[3],
data[4]
);
emit CreditLineMigrated(owner, clAddress, newCl, pool);
}
}
function bulkAddToGoList(GoldfinchConfig newConfig, address[] calldata members) external onlyAdmin {
newConfig.bulkAddToGoList(members);
}
function pauseEverything() internal {
IMigrate(config.creditDeskAddress()).pause();
IMigrate(config.poolAddress()).pause();
IMigrate(config.fiduAddress()).pause();
}
function migrateToNewConfig(GoldfinchConfig newConfig) internal {
uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig);
config.setAddress(key, address(newConfig));
IMigrate(config.creditDeskAddress()).updateGoldfinchConfig();
IMigrate(config.poolAddress()).updateGoldfinchConfig();
IMigrate(config.fiduAddress()).updateGoldfinchConfig();
IMigrate(config.goldfinchFactoryAddress()).updateGoldfinchConfig();
key = uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds);
newConfig.setNumber(key, 24 * 60 * 60);
key = uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays);
newConfig.setNumber(key, 365);
key = uint256(ConfigOptions.Numbers.LeverageRatio);
// 1e18 is the LEVERAGE_RATIO_DECIMALS
newConfig.setNumber(key, 3 * 1e18);
}
function upgradeImplementations(GoldfinchConfig _config, address[] calldata newDeployments) public {
address newPoolAddress = newDeployments[0];
address newCreditDeskAddress = newDeployments[1];
address newFiduAddress = newDeployments[2];
address newGoldfinchFactoryAddress = newDeployments[3];
bytes memory data;
IMigrate pool = IMigrate(_config.poolAddress());
IMigrate creditDesk = IMigrate(_config.creditDeskAddress());
IMigrate fidu = IMigrate(_config.fiduAddress());
IMigrate goldfinchFactory = IMigrate(_config.goldfinchFactoryAddress());
// Upgrade implementations
pool.changeImplementation(newPoolAddress, data);
creditDesk.changeImplementation(newCreditDeskAddress, data);
fidu.changeImplementation(newFiduAddress, data);
goldfinchFactory.changeImplementation(newGoldfinchFactoryAddress, data);
}
function migrateToSeniorPool(GoldfinchConfig newConfig) internal {
IMigrate(config.fiduAddress()).grantRole(MINTER_ROLE, newConfig.seniorPoolAddress());
IMigrate(config.poolAddress()).unpause();
IMigrate(newConfig.poolAddress()).migrateToSeniorPool();
}
function closeOutMigration(GoldfinchConfig newConfig) external onlyAdmin {
IMigrate fidu = IMigrate(newConfig.fiduAddress());
IMigrate creditDesk = IMigrate(newConfig.creditDeskAddress());
IMigrate oldPool = IMigrate(newConfig.poolAddress());
IMigrate goldfinchFactory = IMigrate(newConfig.goldfinchFactoryAddress());
fidu.unpause();
fidu.renounceRole(MINTER_ROLE, address(this));
fidu.renounceRole(OWNER_ROLE, address(this));
fidu.renounceRole(PAUSER_ROLE, address(this));
creditDesk.renounceRole(OWNER_ROLE, address(this));
creditDesk.renounceRole(PAUSER_ROLE, address(this));
oldPool.renounceRole(OWNER_ROLE, address(this));
oldPool.renounceRole(PAUSER_ROLE, address(this));
goldfinchFactory.renounceRole(OWNER_ROLE, address(this));
goldfinchFactory.renounceRole(PAUSER_ROLE, address(this));
config.renounceRole(PAUSER_ROLE, address(this));
config.renounceRole(OWNER_ROLE, address(this));
newConfig.renounceRole(OWNER_ROLE, address(this));
newConfig.renounceRole(PAUSER_ROLE, address(this));
newConfig.renounceRole(GO_LISTER_ROLE, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IMigrate {
function pause() public virtual;
function unpause() public virtual;
function updateGoldfinchConfig() external virtual;
function grantRole(bytes32 role, address assignee) external virtual;
function renounceRole(bytes32 role, address self) external virtual;
// Proxy methods
function transferOwnership(address newOwner) external virtual;
function changeImplementation(address newImplementation, bytes calldata data) external virtual;
function owner() external view virtual returns (address);
// CreditDesk
function migrateV1CreditLine(
address _clToMigrate,
address borrower,
uint256 termEndTime,
uint256 nextDueTime,
uint256 interestAccruedAsOf,
uint256 lastFullPaymentTime,
uint256 totalInterestPaid
) public virtual returns (address, address);
// Pool
function migrateToSeniorPool() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/Pool.sol";
contract TestPool is Pool {
function _getNumShares(uint256 amount) public view returns (uint256) {
return getNumShares(amount);
}
function _usdcMantissa() public pure returns (uint256) {
return usdcMantissa();
}
function _fiduMantissa() public pure returns (uint256) {
return fiduMantissa();
}
function _usdcToFidu(uint256 amount) public pure returns (uint256) {
return usdcToFidu(amount);
}
function _setSharePrice(uint256 newSharePrice) public returns (uint256) {
sharePrice = newSharePrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/Pool.sol";
import "../protocol/core/BaseUpgradeablePausable.sol";
contract FakeV2CreditLine is BaseUpgradeablePausable {
// Credit line terms
address public borrower;
address public underwriter;
uint256 public limit;
uint256 public interestApr;
uint256 public paymentPeriodInDays;
uint256 public termInDays;
uint256 public lateFeeApr;
// Accounting variables
uint256 public balance;
uint256 public interestOwed;
uint256 public principalOwed;
uint256 public termEndTime;
uint256 public nextDueTime;
uint256 public interestAccruedAsOf;
uint256 public writedownAmount;
uint256 public lastFullPaymentTime;
function initialize(
address owner,
address _borrower,
address _underwriter,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) public initializer {
__BaseUpgradeablePausable__init(owner);
borrower = _borrower;
underwriter = _underwriter;
limit = _limit;
interestApr = _interestApr;
paymentPeriodInDays = _paymentPeriodInDays;
termInDays = _termInDays;
lateFeeApr = _lateFeeApr;
interestAccruedAsOf = block.timestamp;
}
function anotherNewFunction() external pure returns (uint256) {
return 42;
}
function authorizePool(address) external view onlyAdmin {
// no-op
return;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "../../interfaces/IGo.sol";
import "../../interfaces/IUniqueIdentity0612.sol";
contract Go is IGo, BaseUpgradeablePausable {
address public override uniqueIdentity;
using SafeMath for uint256;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
GoldfinchConfig public legacyGoList;
uint256[11] public allIdTypes;
event GoldfinchConfigUpdated(address indexed who, address configAddress);
function initialize(
address owner,
GoldfinchConfig _config,
address _uniqueIdentity
) public initializer {
require(
owner != address(0) && address(_config) != address(0) && _uniqueIdentity != address(0),
"Owner and config and UniqueIdentity addresses cannot be empty"
);
__BaseUpgradeablePausable__init(owner);
_performUpgrade();
config = _config;
uniqueIdentity = _uniqueIdentity;
}
function updateGoldfinchConfig() external override onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
function performUpgrade() external onlyAdmin {
return _performUpgrade();
}
function _performUpgrade() internal {
allIdTypes[0] = ID_TYPE_0;
allIdTypes[1] = ID_TYPE_1;
allIdTypes[2] = ID_TYPE_2;
allIdTypes[3] = ID_TYPE_3;
allIdTypes[4] = ID_TYPE_4;
allIdTypes[5] = ID_TYPE_5;
allIdTypes[6] = ID_TYPE_6;
allIdTypes[7] = ID_TYPE_7;
allIdTypes[8] = ID_TYPE_8;
allIdTypes[9] = ID_TYPE_9;
allIdTypes[10] = ID_TYPE_10;
}
/**
* @notice sets the config that will be used as the source of truth for the go
* list instead of the config currently associated. To use the associated config for to list, set the override
* to the null address.
*/
function setLegacyGoList(GoldfinchConfig _legacyGoList) external onlyAdmin {
legacyGoList = _legacyGoList;
}
/**
* @notice Returns whether the provided account is go-listed for use of the Goldfinch protocol
* for any of the UID token types.
* This status is defined as: whether `balanceOf(account, id)` on the UniqueIdentity
* contract is non-zero (where `id` is a supported token id on UniqueIdentity), falling back to the
* account's status on the legacy go-list maintained on GoldfinchConfig.
* @param account The account whose go status to obtain
* @return The account's go status
*/
function go(address account) public view override returns (bool) {
require(account != address(0), "Zero address is not go-listed");
if (_getLegacyGoList().goList(account) || IUniqueIdentity0612(uniqueIdentity).balanceOf(account, ID_TYPE_0) > 0) {
return true;
}
// start loop at index 1 because we checked index 0 above
for (uint256 i = 1; i < allIdTypes.length; ++i) {
uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, allIdTypes[i]);
if (idTypeBalance > 0) {
return true;
}
}
return false;
}
/**
* @notice Returns whether the provided account is go-listed for use of the Goldfinch protocol
* for defined UID token types
* @param account The account whose go status to obtain
* @param onlyIdTypes Array of id types to check balances
* @return The account's go status
*/
function goOnlyIdTypes(address account, uint256[] memory onlyIdTypes) public view override returns (bool) {
require(account != address(0), "Zero address is not go-listed");
GoldfinchConfig goListSource = _getLegacyGoList();
for (uint256 i = 0; i < onlyIdTypes.length; ++i) {
if (onlyIdTypes[i] == ID_TYPE_0 && goListSource.goList(account)) {
return true;
}
uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, onlyIdTypes[i]);
if (idTypeBalance > 0) {
return true;
}
}
return false;
}
/**
* @notice Returns whether the provided account is go-listed for use of the SeniorPool on the Goldfinch protocol.
* @param account The account whose go status to obtain
* @return The account's go status
*/
function goSeniorPool(address account) public view override returns (bool) {
require(account != address(0), "Zero address is not go-listed");
if (account == config.stakingRewardsAddress() || _getLegacyGoList().goList(account)) {
return true;
}
uint256[2] memory seniorPoolIdTypes = [ID_TYPE_0, ID_TYPE_1];
for (uint256 i = 0; i < seniorPoolIdTypes.length; ++i) {
uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, seniorPoolIdTypes[i]);
if (idTypeBalance > 0) {
return true;
}
}
return false;
}
function _getLegacyGoList() internal view returns (GoldfinchConfig) {
return address(legacyGoList) == address(0) ? config : legacyGoList;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/// @dev This interface provides a subset of the functionality of the IUniqueIdentity
/// interface -- namely, the subset of functionality needed by Goldfinch protocol contracts
/// compiled with Solidity version 0.6.12.
interface IUniqueIdentity0612 {
function balanceOf(address account, uint256 id) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/GoldfinchConfig.sol";
contract TestTheConfig {
address public poolAddress = 0xBAc2781706D0aA32Fb5928c9a5191A13959Dc4AE;
address public clImplAddress = 0xc783df8a850f42e7F7e57013759C285caa701eB6;
address public goldfinchFactoryAddress = 0x0afFE1972479c386A2Ab21a27a7f835361B6C0e9;
address public fiduAddress = 0xf3c9B38c155410456b5A98fD8bBf5E35B87F6d96;
address public creditDeskAddress = 0xeAD9C93b79Ae7C1591b1FB5323BD777E86e150d4;
address public treasuryReserveAddress = 0xECd9C93B79AE7C1591b1fB5323BD777e86E150d5;
address public trustedForwarderAddress = 0x956868751Cc565507B3B58E53a6f9f41B56bed74;
address public cUSDCAddress = 0x5B281A6DdA0B271e91ae35DE655Ad301C976edb1;
address public goldfinchConfigAddress = address(8);
function testTheEnums(address configAddress) public {
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TransactionLimit), 1);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit), 2);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit), 3);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.ReserveDenominator), 4);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator), 5);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays), 6);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays), 7);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds), 8);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays), 9);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LeverageRatio), 10);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Fidu), fiduAddress);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Pool), poolAddress);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CreditDesk), creditDeskAddress);
GoldfinchConfig(configAddress).setAddress(
uint256(ConfigOptions.Addresses.GoldfinchFactory),
goldfinchFactoryAddress
);
GoldfinchConfig(configAddress).setAddress(
uint256(ConfigOptions.Addresses.TrustedForwarder),
trustedForwarderAddress
);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CUSDCContract), cUSDCAddress);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig), goldfinchConfigAddress);
GoldfinchConfig(configAddress).setTreasuryReserve(treasuryReserveAddress);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/core/GoldfinchConfig.sol";
contract TestGoldfinchConfig is GoldfinchConfig {
function setAddressForTest(uint256 addressKey, address newAddress) public {
addresses[addressKey] = newAddress;
}
} | If no money left to apply, or don't need any changes, return the original amounts We don't have enough money to adjust share price to the desired level. So just use whatever amount is left | function applyToSharePrice(
uint256 amountRemaining,
uint256 currentSharePrice,
uint256 desiredAmount,
uint256 totalShares
) public pure returns (uint256, uint256) {
if (amountRemaining == 0 || desiredAmount == 0) {
return (amountRemaining, currentSharePrice);
}
if (amountRemaining < desiredAmount) {
desiredAmount = amountRemaining;
}
uint256 sharePriceDifference = usdcToSharePrice(desiredAmount, totalShares);
return (amountRemaining.sub(desiredAmount), currentSharePrice.add(sharePriceDifference));
}
| 6,235,170 | [
1,
2047,
1158,
15601,
2002,
358,
2230,
16,
578,
2727,
1404,
1608,
1281,
3478,
16,
327,
326,
2282,
30980,
1660,
2727,
1404,
1240,
7304,
15601,
358,
5765,
7433,
6205,
358,
326,
6049,
1801,
18,
6155,
2537,
999,
15098,
3844,
353,
2002,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
28681,
9535,
5147,
12,
203,
565,
2254,
5034,
3844,
11429,
16,
203,
565,
2254,
5034,
783,
9535,
5147,
16,
203,
565,
2254,
5034,
6049,
6275,
16,
203,
565,
2254,
5034,
2078,
24051,
203,
225,
262,
1071,
16618,
1135,
261,
11890,
5034,
16,
2254,
5034,
13,
288,
203,
565,
309,
261,
8949,
11429,
422,
374,
747,
6049,
6275,
422,
374,
13,
288,
203,
1377,
327,
261,
8949,
11429,
16,
783,
9535,
5147,
1769,
203,
565,
289,
203,
565,
309,
261,
8949,
11429,
411,
6049,
6275,
13,
288,
203,
1377,
6049,
6275,
273,
3844,
11429,
31,
203,
565,
289,
203,
565,
2254,
5034,
7433,
5147,
16220,
273,
584,
7201,
774,
9535,
5147,
12,
30458,
6275,
16,
2078,
24051,
1769,
203,
565,
327,
261,
8949,
11429,
18,
1717,
12,
30458,
6275,
3631,
783,
9535,
5147,
18,
1289,
12,
14419,
5147,
16220,
10019,
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
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2 <0.8.0;
pragma experimental ABIEncoderV2;
import "./Erc721RaribleInterface.sol";
/**
* @title Cross Chain Transfer for an NFT.
* @dev 1. Sender apporves nft for the contract.
* @dev 2. Sender init tryCrossChainTransfer ->
* @dev oracle gets event and init nft creation
* @dev for the same owner in different ethereum friendly chain.
* @dev The NFT collection (i.e. erc721 contract) ought to exist in the desired network.
* @dev Thus, erc721 contract deployer ought to deploy the same contract in desired chain.
* @dev For now it is kinda more about Rarible erc721 Cross Chain Transfer
*/
contract Erc721CrossChainTransfer {
/// @dev Emit event is for our oracles
/// @dev todo: add argument to specify what contract emits: e.g. Rarible or OpenSea erc721, etc
event TryCrossChainTransfer(uint256 toChain, address indexed nftContract, uint256 nftToken,
address nftOwner, string nftURI, LibPart.Part[] raribleRoyalties);
function tryCrossChainTransfer(uint256 _toChainId, address _nftContract, uint256 _nftToken) external {
// todo: payable to pay minting in other chain. We want our contract "service" to be profitable.
// todo: check if nft has desired method (mintAndTransfer) in the desired chain. (oracles should check it)
// todo: check if getRaribleV2Royalties, tokenURI
// todo: add signature
// todo: idempotent logic: user can retry this method, but nft owner changed coz of success transfer
// so, we should possible have mapping in contract, but rather this such a business logic could be
// implemented in oracles instead, thus, we leave contract as light as possible.
Erc721RaribleInterface erc721Interface;
erc721Interface = Erc721RaribleInterface(_nftContract);
require(erc721Interface.getApproved(_nftToken) == address(this), "Erc721 token is not approved for current contract");
address _nftOwner = erc721Interface.ownerOf(_nftToken);
string memory _nftURI = erc721Interface.tokenURI(_nftToken);
LibPart.Part[] memory _raribleRoyalties = erc721Interface.getRaribleV2Royalties(_nftToken);
if (_nftOwner != address(this)) {
erc721Interface.transferFrom(_nftOwner, address(this), _nftToken);
// todo: on else emit another event to init retry action (why: check above comments)
}
emit TryCrossChainTransfer(_toChainId, _nftContract, _nftToken, _nftOwner, _nftURI, _raribleRoyalties);
}
}
| * @title Cross Chain Transfer for an NFT. @dev 1. Sender apporves nft for the contract. @dev 2. Sender init tryCrossChainTransfer -> @dev oracle gets event and init nft creation @dev for the same owner in different ethereum friendly chain. @dev The NFT collection (i.e. erc721 contract) ought to exist in the desired network. @dev Thus, erc721 contract deployer ought to deploy the same contract in desired chain. @dev For now it is kinda more about Rarible erc721 Cross Chain Transfer/ | contract Erc721CrossChainTransfer {
event TryCrossChainTransfer(uint256 toChain, address indexed nftContract, uint256 nftToken,
address nftOwner, string nftURI, LibPart.Part[] raribleRoyalties);
pragma solidity >=0.6.2 <0.8.0;
function tryCrossChainTransfer(uint256 _toChainId, address _nftContract, uint256 _nftToken) external {
Erc721RaribleInterface erc721Interface;
erc721Interface = Erc721RaribleInterface(_nftContract);
require(erc721Interface.getApproved(_nftToken) == address(this), "Erc721 token is not approved for current contract");
address _nftOwner = erc721Interface.ownerOf(_nftToken);
string memory _nftURI = erc721Interface.tokenURI(_nftToken);
LibPart.Part[] memory _raribleRoyalties = erc721Interface.getRaribleV2Royalties(_nftToken);
if (_nftOwner != address(this)) {
erc721Interface.transferFrom(_nftOwner, address(this), _nftToken);
}
emit TryCrossChainTransfer(_toChainId, _nftContract, _nftToken, _nftOwner, _nftURI, _raribleRoyalties);
}
function tryCrossChainTransfer(uint256 _toChainId, address _nftContract, uint256 _nftToken) external {
Erc721RaribleInterface erc721Interface;
erc721Interface = Erc721RaribleInterface(_nftContract);
require(erc721Interface.getApproved(_nftToken) == address(this), "Erc721 token is not approved for current contract");
address _nftOwner = erc721Interface.ownerOf(_nftToken);
string memory _nftURI = erc721Interface.tokenURI(_nftToken);
LibPart.Part[] memory _raribleRoyalties = erc721Interface.getRaribleV2Royalties(_nftToken);
if (_nftOwner != address(this)) {
erc721Interface.transferFrom(_nftOwner, address(this), _nftToken);
}
emit TryCrossChainTransfer(_toChainId, _nftContract, _nftToken, _nftOwner, _nftURI, _raribleRoyalties);
}
}
| 2,575,526 | [
1,
13941,
7824,
12279,
364,
392,
423,
4464,
18,
225,
404,
18,
15044,
595,
280,
3324,
290,
1222,
364,
326,
6835,
18,
225,
576,
18,
15044,
1208,
775,
13941,
3893,
5912,
317,
225,
20865,
5571,
871,
471,
1208,
290,
1222,
6710,
225,
364,
326,
1967,
3410,
316,
3775,
13750,
822,
379,
13118,
2687,
18,
225,
1021,
423,
4464,
1849,
261,
77,
18,
73,
18,
6445,
71,
27,
5340,
6835,
13,
320,
9540,
358,
1005,
316,
326,
6049,
2483,
18,
225,
22073,
16,
6445,
71,
27,
5340,
6835,
7286,
264,
320,
9540,
358,
7286,
326,
1967,
6835,
316,
6049,
2687,
18,
225,
2457,
2037,
518,
353,
3846,
69,
1898,
2973,
534,
297,
1523,
6445,
71,
27,
5340,
19742,
7824,
12279,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
512,
1310,
27,
5340,
13941,
3893,
5912,
288,
203,
203,
565,
871,
6161,
13941,
3893,
5912,
12,
11890,
5034,
358,
3893,
16,
1758,
8808,
290,
1222,
8924,
16,
2254,
5034,
290,
1222,
1345,
16,
203,
3639,
1758,
290,
1222,
5541,
16,
533,
290,
1222,
3098,
16,
10560,
1988,
18,
1988,
8526,
436,
297,
1523,
54,
13372,
2390,
606,
1769,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
26,
18,
22,
411,
20,
18,
28,
18,
20,
31,
203,
565,
445,
775,
13941,
3893,
5912,
12,
11890,
5034,
389,
869,
3893,
548,
16,
1758,
389,
82,
1222,
8924,
16,
2254,
5034,
389,
82,
1222,
1345,
13,
3903,
288,
203,
3639,
512,
1310,
27,
5340,
54,
297,
1523,
1358,
6445,
71,
27,
5340,
1358,
31,
203,
3639,
6445,
71,
27,
5340,
1358,
273,
512,
1310,
27,
5340,
54,
297,
1523,
1358,
24899,
82,
1222,
8924,
1769,
203,
203,
3639,
2583,
12,
12610,
27,
5340,
1358,
18,
588,
31639,
24899,
82,
1222,
1345,
13,
422,
1758,
12,
2211,
3631,
315,
41,
1310,
27,
5340,
1147,
353,
486,
20412,
364,
783,
6835,
8863,
203,
3639,
1758,
389,
82,
1222,
5541,
273,
6445,
71,
27,
5340,
1358,
18,
8443,
951,
24899,
82,
1222,
1345,
1769,
203,
3639,
533,
3778,
389,
82,
1222,
3098,
273,
6445,
71,
27,
5340,
1358,
18,
2316,
3098,
24899,
82,
1222,
1345,
1769,
203,
3639,
10560,
1988,
18,
1988,
8526,
3778,
389,
86,
297,
1523,
54,
13372,
2390,
606,
273,
6445,
71,
27,
5340,
1358,
18,
588,
54,
297,
1523,
58,
22,
54,
2
] |
./partial_match/1/0x449962b884D2F818edb5d197E8572b42b6De99Ef/sources/FRS.sol | Constant and pseudo constant valuesVariables related to the day indexOther mappingsTiming variablesExternal contracts | contract FRS is Ownable {
using SafeMath for uint256;
syncToken=Sync(token);
totalDailyRewards[currentDayIndex]=INITIAL_DAILY_REWARD;
maintainers[0]=0x464376466Ea0494Ff0bC90260c46f98c56c8c746;
maintainers[1]=0x2fFD215E32bF25366172a5470FCEA3182C6c718F;
maintainers[2]=0xaF35f3685C92b83E8e64880441FA39FE2B6Fcf48;
maintainers[3]=0x5ed7D8e2089B2B0e15439735B937CeC5F0ae811B;
maintainers[4]=0x73b8c96A1131C19B6A0Dc972099eE5E2B328f66B;
maintainers[5]=0x8AB0b38B5331ADAe0EDfB713c714521964C5bCCC;
}
| 9,319,565 | [
1,
6902,
471,
12454,
5381,
924,
6158,
3746,
358,
326,
2548,
770,
8290,
7990,
25377,
3152,
6841,
20092,
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,
16351,
478,
13225,
353,
14223,
6914,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
203,
203,
203,
203,
565,
3792,
1345,
33,
4047,
12,
2316,
1769,
203,
565,
2078,
40,
12857,
17631,
14727,
63,
2972,
4245,
1016,
65,
33,
28497,
67,
40,
6575,
61,
67,
862,
21343,
31,
203,
565,
11566,
8234,
63,
20,
65,
33,
20,
92,
24,
1105,
6418,
1105,
6028,
41,
69,
3028,
11290,
42,
74,
20,
70,
39,
29,
3103,
4848,
71,
8749,
74,
10689,
71,
4313,
71,
28,
71,
5608,
26,
31,
203,
565,
11566,
8234,
63,
21,
65,
33,
20,
92,
22,
74,
16894,
22,
3600,
41,
1578,
70,
42,
2947,
5718,
26,
28406,
69,
6564,
7301,
42,
1441,
37,
23,
28246,
39,
26,
71,
27,
2643,
42,
31,
203,
565,
11566,
8234,
63,
22,
65,
33,
20,
6995,
42,
4763,
74,
5718,
7140,
39,
9975,
70,
10261,
41,
28,
73,
1105,
5482,
3028,
9803,
2046,
5520,
8090,
22,
38,
26,
42,
8522,
8875,
31,
203,
565,
11566,
8234,
63,
23,
65,
33,
20,
92,
25,
329,
27,
40,
28,
73,
3462,
6675,
38,
22,
38,
20,
73,
29003,
5520,
27,
4763,
38,
29,
6418,
39,
73,
39,
25,
42,
20,
8906,
28,
2499,
38,
31,
203,
565,
11566,
8234,
63,
24,
65,
33,
20,
92,
9036,
70,
28,
71,
10525,
37,
2499,
6938,
39,
3657,
38,
26,
37,
20,
40,
71,
10580,
3462,
2733,
73,
41,
25,
41,
22,
38,
1578,
28,
74,
6028,
38,
31,
203,
565,
11566,
8234,
63,
25,
2
] |
./partial_match/1/0x7512F36cE571Ba1C63326BEa9eE252e129092D4C/sources/HPBD.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Happy Birthday Elon Musk", "HPBD") {
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 = 10;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 20;
uint256 _sellMarketingFee = 10;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 20;
uint256 totalSupply = 286_420_690_911_007 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(marketingWallet, 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);
| 3,596,214 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
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,
3885,
1435,
4232,
39,
3462,
2932,
44,
438,
2074,
605,
10542,
2881,
512,
9379,
490,
407,
79,
3113,
315,
2500,
18096,
7923,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
203,
5411,
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,
203,
3639,
11272,
203,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
1728,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
374,
31,
203,
2
] |
// 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 v4.4.1 (finance/PaymentSplitter.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/utils/SafeERC20.sol";
import "../utils/Address.sol";
import "../utils/Context.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.
*
* NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
* tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
* to run tests before sending real value to this contract.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
mapping(IERC20 => uint256) private _erc20TotalReleased;
mapping(IERC20 => mapping(address => uint256)) private _erc20Released;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
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 total amount of `token` already released. `token` should be the address of an IERC20
* contract.
*/
function totalReleased(IERC20 token) public view returns (uint256) {
return _erc20TotalReleased[token];
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
* IERC20 contract.
*/
function released(IERC20 token, address account) public view returns (uint256) {
return _erc20Released[token][account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + totalReleased();
uint256 payment = _pendingPayment(account, totalReceived, released(account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] += payment;
_totalReleased += payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
* percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
* contract.
*/
function release(IERC20 token, address account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
uint256 payment = _pendingPayment(account, totalReceived, released(token, account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_erc20Released[token][account] += payment;
_erc20TotalReleased[token] += payment;
SafeERC20.safeTransfer(token, account, payment);
emit ERC20PaymentReleased(token, account, payment);
}
/**
* @dev internal logic for computing the pending payment of an `account` given the token historical balances and
* already released amounts.
*/
function _pendingPayment(
address account,
uint256 totalReceived,
uint256 alreadyReleased
) private view returns (uint256) {
return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
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 making 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: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.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 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'
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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_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
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// 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 v4.4.1 (utils/Address.sol)
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
// 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 (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;
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 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
// 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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
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/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/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 ERC721Sequential is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Total number of tokens burned
uint256 internal _burnCount;
// Array of all tokens storing the owner's address
address[] internal _tokens = [address(0x0)];
// 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);
}
function totalMinted() public view returns (uint256) {
return _tokens.length - 1;
}
function totalSupply() public view returns (uint256) {
return totalMinted() - _burnCount;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This is implementation is O(n) and should not be
* called by other contracts.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
returns (uint256)
{
uint256 currentIndex = 0;
for (uint256 i = 0; i < _tokens.length; i++) {
if (_tokens[i] == owner) {
if (currentIndex == index) {
return i;
}
currentIndex += 1;
}
}
revert("ERC721Enumerable: owner index out of bounds");
}
/**
* @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 = _tokens[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 = ERC721Sequential.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 _tokens[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 = ERC721Sequential.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) internal virtual {
_safeMint(to, "");
}
/**
* @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, bytes memory _data) internal virtual {
require(
_checkOnERC721Received(address(0), to, _tokens.length, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
_mint(to);
}
/**
* @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) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
uint256 tokenId = _tokens.length;
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_tokens.push(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 = ERC721Sequential.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_burnCount++;
_balances[owner] -= 1;
_tokens[tokenId] = address(0);
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(
ERC721Sequential.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;
_tokens[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(ERC721Sequential.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.9;
// ███╗ ██╗███████╗██████╗ ██╗ ██╗ ██████╗ ██╗ ██╗███████╗
// ████╗ ██║██╔════╝██╔══██╗██║ ██║██╔═══██╗██║ ██║██╔════╝
// ██╔██╗ ██║█████╗ ██████╔╝██║ ██║██║ ██║██║ ██║███████╗
// ██║╚██╗██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██║ ██║██║ ██║╚════██║
// ██║ ╚████║███████╗██║ ██║ ╚████╔╝ ╚██████╔╝╚██████╔╝███████║
// ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚══════╝
// work with us: nervous.net // [email protected] // [email protected]
// ██╗ ██╗
// ╚██╗██╔╝
// ╚███╔╝
// ██╔██╗
// ██╔╝ ██╗
// ╚═╝ ╚═╝
//
//__/\\\______________/\\\__/\\\________/\\\____/\\\\\\\\\______/\\\\\\\\\\\\\_______/\\\\\\\\\\\___
// _\/\\\_____________\/\\\_\/\\\_______\/\\\__/\\\///////\\\___\/\\\/////////\\\___/\\\/////////\\\_
// _\/\\\_____________\/\\\_\//\\\______/\\\__\/\\\_____\/\\\___\/\\\_______\/\\\__\//\\\______\///__
// _\//\\\____/\\\____/\\\___\//\\\____/\\\___\/\\\\\\\\\\\/____\/\\\\\\\\\\\\\/____\////\\\_________
// __\//\\\__/\\\\\__/\\\_____\//\\\__/\\\____\/\\\//////\\\____\/\\\/////////_________\////\\\______
// ___\//\\\/\\\/\\\/\\\_______\//\\\/\\\_____\/\\\____\//\\\___\/\\\_____________________\////\\\___
// ____\//\\\\\\//\\\\\_________\//\\\\\______\/\\\_____\//\\\__\/\\\______________/\\\______\//\\\__
// _____\//\\\__\//\\\___________\//\\\_______\/\\\______\//\\\_\/\\\_____________\///\\\\\\\\\\\/___
// ______\///____\///_____________\///________\///________\///__\///________________\///////////_____
// __ __ __ ____ __
// /\ \ /\ \ __/\ \ /\ _`\ /\ \
// \ \ \____ __ __ \ \ \/\ \ \ \ __ _ __ _____\ \,\L\_\ ___ __ __ ___ \_\ \
// \ \ '__`\/\ \/\ \ \ \ \ \ \ \ \ /'__`\ /\`'__\/\ '__`\/_\__ \ / __`\/\ \/\ \ /' _ `\ /'_` \
// \ \ \L\ \ \ \_\ \ \ \ \_/ \_\ \/\ \L\.\_\ \ \/ \ \ \L\ \/\ \L\ \/\ \L\ \ \ \_\ \/\ \/\ \/\ \L\ \
// \ \_,__/\/`____ \ \ `\___x___/\ \__/.\_\\ \_\ \ \ ,__/\ `\____\ \____/\ \____/\ \_\ \_\ \___,_\
// \/___/ `/___/> \ '\/__//__/ \/__/\/_/ \/_/ \ \ \/ \/_____/\/___/ \/___/ \/_/\/_/\/__,_ /
// /\___/ \ \_\
// \/__/ \/_/
//
//
//
// -----------------------------------------------------------------------------
//
//
//
// This is Nervous NFT V3. Gas Friendly, Feature Rich, ERC721 future compatible.
//
// .|\ .-:.
// / / '._____/ / '. : .
// . . ________/ / '.__/ / '. : .:'
// .-'-. | -----/_/_/_/ /'-. ',='--. ': .:'
// _ .----""""""-^-^--' () __ = / '-._ '.==='-. :====.__.:'
// .'_/ = _ = .-. = /""/ /_/ /""/ /"'---._ '--u_:.===="| __: :'\
// .'.'/ / / / / /__/ = /__/ /_/'.-.' '. . . -.-.:|<:::::' \
// ..' / "" '"'= // = / """----' . (. ' ./#|######'\ \
// ..--/ = = = = = / . __ ' /##.'#######\\ \
// || (-----N-E-R-V-O-U-S---v3------------(--------.___._ ( ;###|#########)---->-"""" ascii art by mga
// '' \ _--.-.. __ = = \ __ ___'"""-(---"\########// /
// ''.-\ \ \ \ \ '\' .-------._____. ' \ "\\"" \\###\######// /
// '.'.\ \ \ \ \ '\' \ \ \ \ \\ ' .- ""'' "" \\.-.\---='/ /
// '._\ \ \ \ \ '\' \ \ \ \ \\ = ' \""'-\".-7-. "\"" /-._/
// '-^-\_\__\ '\' \ \ \ \ \\ ' .' .---"""""(__ "-_\__---""--.
// """"""""--^---^___\___\\ :._____------"""""""" "-_ "
// """""
//
// Thanks to Galactic and 0x420 for their gas friendly ERC721S implementation.
//
//
//
// -----------------------------------------------------------------------------
//
import "./ERC721S.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/finance/PaymentSplitter.sol";
contract NervousNFT is
ERC721Sequential,
ReentrancyGuard,
PaymentSplitter,
Ownable
{
using Strings for uint256;
using ECDSA for bytes32;
mapping(bytes => uint256) private usedTickets;
uint256 public immutable maxSupply;
uint256 public constant MINT_PRICE = 0.08 ether;
uint256 public constant MAX_MINTS = 9;
string public baseURI;
bool public mintingEnabled = true;
uint256 public startPresaleDate = 1642438800; // January 17, 9 am PST
uint256 public startPresaleAct2Date = 1642449600; // January 17, 12 pm PST
uint256 public startPresaleAct3Date = 1642460400; // January 17, 3 pm PST
uint256 public startPresaleAct4Date = 1642482000; // January 17, 9 pm PST
uint256 public endPresaleDate = 1642525199; // January 18, 8:59:59 am PST
uint256 public startPublicMintDate = 1642525200; // January 18, 9 am PST
uint256 public constant MAX_ACT1_PRESALE_MINTS = 3;
uint256 public constant MAX_ACT2_PRESALE_MINTS = 2;
uint256 public constant MAX_ACT3_PRESALE_MINTS = 1;
uint256 public constant MAX_ACT4_PRESALE_MINTS = 1;
address public act1PresaleSigner;
address public act2PresaleSigner;
address public act3PresaleSigner;
address public act4PresaleSigner;
string public constant R =
"We are Nervous. Are you? Let us help you with your next NFT Project -> [email protected]";
constructor(
string memory name,
string memory symbol,
string memory _initBaseURI,
uint256 _maxSupply,
address _act1PresaleSigner,
address _act2PresaleSigner,
address _act3PresaleSigner,
address _act4PresaleSigner,
address[] memory payees,
uint256[] memory shares
) ERC721Sequential(name, symbol) PaymentSplitter(payees, shares) {
baseURI = _initBaseURI;
maxSupply = _maxSupply;
act1PresaleSigner = _act1PresaleSigner;
act2PresaleSigner = _act2PresaleSigner;
act3PresaleSigner = _act3PresaleSigner;
act4PresaleSigner = _act4PresaleSigner;
}
/* Minting */
function toggleMinting() public onlyOwner {
mintingEnabled = !mintingEnabled;
}
function mint(uint256 numTokens, bytes memory pass)
public
payable
nonReentrant
{
require(mintingEnabled, "Minting isn't enabled");
require(totalMinted() + numTokens <= maxSupply, "Sold Out");
require(
numTokens > 0 && numTokens <= MAX_MINTS,
"Machine can dispense a minimum of 1, maximum of 9 tokens"
);
require(
msg.value >= numTokens * MINT_PRICE,
"Insufficient Payment: Amount of Ether sent is not correct."
);
if (hasPreSaleStarted()) {
uint256 presaleActForTicket = firstEligibleActForTicket(pass);
require(
presaleActForTicket <= currentPresaleAct(),
"Invalid ticket for current presale act"
);
uint256 mintablePresale = calculateMintablePresale(
presaleActForTicket,
pass
);
require(numTokens <= mintablePresale, "Minting Too Many Presale");
useTicket(pass, numTokens);
} else {
require(hasPublicSaleStarted(), "Sale hasn't started");
}
for (uint256 i = 0; i < numTokens; i++) {
_safeMint(msg.sender);
}
}
function calculateMintablePresale(
uint256 _presaleActForTicket,
bytes memory _pass
) internal view returns (uint256) {
uint256 maxMintForPresale;
if (_presaleActForTicket == 1) {
maxMintForPresale = MAX_ACT1_PRESALE_MINTS;
} else if (_presaleActForTicket == 2) {
maxMintForPresale = MAX_ACT2_PRESALE_MINTS;
} else if (_presaleActForTicket == 3) {
maxMintForPresale = MAX_ACT3_PRESALE_MINTS;
} else if (_presaleActForTicket == 4) {
maxMintForPresale = MAX_ACT4_PRESALE_MINTS;
} else {
revert("Invalid Presale Act");
}
require(usedTickets[_pass] < maxMintForPresale, "Ticket already used");
return maxMintForPresale - usedTickets[_pass];
}
/* Ticket Handling */
// Thanks for 0x420 and their solid implementation of tickets in the OG:DG drop.
function getHash() internal view returns (bytes32) {
return keccak256(abi.encodePacked("NERVOUS", msg.sender));
}
function recover(bytes32 hash, bytes memory signature)
internal
pure
returns (address)
{
return hash.toEthSignedMessageHash().recover(signature);
}
function firstEligibleActForTicket(bytes memory pass)
internal
view
returns (uint256)
{
bytes32 hash = getHash();
address signer = recover(hash, pass);
if (signer == act1PresaleSigner) {
return 1;
} else if (signer == act2PresaleSigner) {
return 2;
} else if (signer == act3PresaleSigner) {
return 3;
} else if (signer == act4PresaleSigner) {
return 4;
} else {
revert("Invalid Ticket");
}
}
function currentPresaleAct() public view returns (uint256) {
if (hasPreSaleStarted()) {
if (block.timestamp >= startPresaleAct4Date) {
return 4;
} else if (block.timestamp >= startPresaleAct3Date) {
return 3;
} else if (block.timestamp >= startPresaleAct2Date) {
return 2;
} else {
return 1;
}
} else {
return 0;
}
}
function useTicket(bytes memory pass, uint256 quantity) internal {
usedTickets[pass] += quantity;
}
/* Sale state */
function hasPublicSaleStarted() public view returns (bool) {
if (startPublicMintDate <= block.timestamp) {
return true;
} else {
return false;
}
}
function hasPreSaleStarted() public view returns (bool) {
if (
startPresaleDate <= block.timestamp &&
endPresaleDate >= block.timestamp
) {
return true;
} else {
return false;
}
}
/* set the dates */
function setPresaleDate(uint256 _startPresaleDate, uint256 _endPresaleDate)
external
onlyOwner
{
startPresaleDate = _startPresaleDate;
endPresaleDate = _endPresaleDate;
}
function setPresaleAct2Date(uint256 _startPresaleAct2Date)
external
onlyOwner
{
startPresaleAct2Date = _startPresaleAct2Date;
}
function setPresaleAct3Date(uint256 _startPresaleAct3Date)
external
onlyOwner
{
startPresaleAct3Date = _startPresaleAct3Date;
}
function setPresaleAct4Date(uint256 _startPresaleAct4Date)
external
onlyOwner
{
startPresaleAct4Date = _startPresaleAct4Date;
}
function setPublicSaleDate(uint256 _startPublicMintDate)
external
onlyOwner
{
startPublicMintDate = _startPublicMintDate;
}
/* set signers */
function setAct1PresaleSigner(address _presaleSigner) external onlyOwner {
act1PresaleSigner = _presaleSigner;
}
function setAct2PresaleSigner(address _preSaleSigner) external onlyOwner {
act2PresaleSigner = _preSaleSigner;
}
function setAct3PresaleSigner(address _preSaleSigner) external onlyOwner {
act3PresaleSigner = _preSaleSigner;
}
function setAct4PresaleSigner(address _preSaleSigner) external onlyOwner {
act4PresaleSigner = _preSaleSigner;
}
// /* Magic */
function magicMint(uint256 numTokens) external onlyOwner {
require(
totalMinted() + numTokens <= maxSupply,
"Exceeds maximum token supply."
);
require(
numTokens > 0 && numTokens <= 100,
"Machine can dispense a minimum of 1, maximum of 100 tokens"
);
for (uint256 i = 0; i < numTokens; i++) {
_safeMint(msg.sender);
}
}
function magicGift(address[] calldata receivers) external onlyOwner {
uint256 numTokens = receivers.length;
require(
totalMinted() + numTokens <= maxSupply,
"Exceeds maximum token supply."
);
for (uint256 i = 0; i < numTokens; i++) {
_safeMint(receivers[i]);
}
}
/* Utility */
/* URL Utility */
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string memory _baseTokenURI) external onlyOwner {
baseURI = _baseTokenURI;
}
/* eth handlers */
function withdraw(address payable account) public virtual {
release(account);
}
function withdrawERC20(IERC20 token, address to) external onlyOwner {
token.transfer(to, token.balanceOf(address(this)));
}
}
//
// /&@@@@@@@@@@@@/
// &&@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@%
// @@@@@@@@&%%%@@@@@@@@@@@@@@@@@@
// @@@@&&&&&&&&&&&&&&%@@@@@@@@@@@@.
// @@&&&&##########&&%%%@@@@@@@@@@
// %#&&&##############%%%%@@@@#@@@@
// %%&#################%%%%@@@##(@
// (#&%################@%%#%######
// #&&#################%%%%#####,
// %%&#################%%%%#####
// #&%########/#######%(%#####
// #&&#######////#####%#%####
// /(/(#####(/. %&&#######/////###&%#####%
// &&&@@@%@@#@################# #&&#######/////###%%####@
// /&&@@@@@@%@@#@@#@###################### %&&######//////##%%####&
// &&&@@@@@@@@@@@@&%%%%%%%%%%%%%%%%%%############ %&&######/////(#&%%###(
// &&@@@@@@@@@&%%%%&@&(###########%&%%%%%%&&########### #&@#####//////#@%%###
// &@@@@@@@@&&&@@###########################@&&&&&########## &&######/////#@%####
// @@@@@@@@@&&&####################################&&&&(######## &&#####/////#@%###@
// @@@@@@@@@&&&&&&@@&,,&@@@@&&&########################&&&&######## %&@###(/////#&%###
// [email protected]@@&#########///(#####&&&####### &&####/////@%###@
// @@&%#######////##@&&(##### &&&/##/////@%##@
// *@&@#####////#%&&##### *########(, &&@#(/////@&###
// #&&####///#&#&&##########################///@&%#(%
// ##&#&%%#################################&##%(
// #(&(##%####################///////////////*/*#####
// %%##&#(%%################//////////////////////****//**
// /&#%&&#&&%&############////#/////////////////////***/*//*
// %%%%&&(&&&%&%%#######%@@@@@@@@@@@///////////////////***/**/*
// #@@@&&&&&@&&&%%%@%%%%/@**///////////////////////////////**/**/
// /*####@&&&&&&&&&&%%&#(//////////////////////////////////////*/*
// /*######&&&&&&&&&&&&//((((/////////////////////////////////////#
// .*(######%&&&&&&&&&&##(#/((((/@@@ /////////////////////////////*
// **###&&@ @&&&&&&&&&##/##((((((&&&@@@///////////////////////////(
// **####%&&%#&&&&&&&&#######((((((////////////////////////////////%
// **########&%&##### /@#((((/////////////////%@/////////////,
// &% **######( [email protected]@, */@&@@&(/////////////////////////@////@
// (, @%*##### ...... *@ [email protected] #///////////@#/////////////////
// #. **#### [email protected]@@@@@@,%&%* .... .//////////////////@//////////.
// & */#### [email protected]@... [email protected] (///////////////////////((/((%
// * **#####*[email protected]@ ... /////////////////////(//(/(@
// */#####/*,... ./ @//////////////((((((((/((/@@
// /######**..&. ((% .. @((((((((((((((((((((((((/@@
// #######@&***,,,&@@%#######################@@@
// %#############################@@@@@@@#
// &&@ #&@@@@@@@@@@@@@@@@@@@@@@@@@@
// @ @ @@&&@ @@@@@@@@#%@@@@@@@@@@@@@@@@@@@
// &@ && @@@@@# @@@@@@@@@@&&&@@@@@@@@@@@@@@@@@@@@
// @&@ &&& @@@@@@@ %@&&&&&&@@@@@@@@@@@@@@@@@@@@@@@@%&@@@@@@@@@@@@@@@@@@@@@@@%#////,
// ,@@@* &&&@ @@@@@@@@ @&&&@@&&@@@@@@@@@@@@@@@@@@@@@@@@@#@@@@*//////////////////////*@@@@@@&&@/////
// @@@@& @@&&@@ @@@@@@@&&&&&&&&@@@@@@@@@&&&&&&&&&&@@@@@@@@%@@@///////////*******/***/****////*@@@&%&&(////
// &, @@@@@% @@&&&@@(@@@@@&&&&&&&&@@@@@@@&&&&&@@@@@@@@@@@@@@@ &%@ //////***/***////******/***//******//@@@&&&&&////,
// .&@@ @@@@@@@@@@@@@@@@@@@@@&&&&&@@@@@@@@@@@@@@@@@@@@@@@@&&&&&%# ////////*****(/***////**////////////////*@@@@&&&&&////
// &&@@ @@@@@@////@@@@@@@@@@@@&&@@@@@@@@@@@@@@&@@@&&&&&&&&&&&@@ (/////////*/***/#(/////////////////////////#@@@@&&&&&&////
// @@@@#/ @@(((*/////////@@@@@@@@@@@@@@@@@@@@@(@&&&&&&&&&&&@@@@@@ ////%%//////////%////*//////////(/////#////////@@@@@&&&&&%////
// , @@@##//(((/////////////////@@@@@@@@@@@@@@@&&@&@@@@@&&@@@@@@@@@ ///%%%%#//*////////(/////*///////@////**/////*///@@@@@@&&&&&&////
// @#* @@##/////////////////////////@@@@@@@@@@@@&&&&@@&&@@@@@@@@@@@ ///%*%%%*.///@///////@(@/////#///////&&@@///////%**@@@@@@&&&&&&&///
// @##/##&###//////////////////////*////@@@@@@@@@@@@&&@@@@@@@@@@@@@@ //%/%%%%....//@.///#//*&@/@@/////#//////&&&&&&&&&&&@@@@@@@&&&&&&&///
// / .###/////@//////////////////////****/////@@@@@@@@@@@@@@@@@@@@@@@@@ ///%%%%%....../@@..&////&&@&/@@@@////*/////&&&&&&&&&@&&&&@@&&&&&&&///
// @#/#####(/%/////////%(/(((((///////////***//////@@@@@@@@@@@@@@@@@@@@@@@ //%%%%%[email protected]&&&../[email protected]@@@@#/@@@&@&&&&@@@@////*///%&&&&@&&&&&%&@@@@@@////
// ######(/////////////%*/@.......... #(/////////////////&@@@@@@@@@@@@@@@@@@@@.*/%%(/%@//(/,[email protected]@@@@@@&&&&&@&&&&&&%&&&@@@@@&&@@@@@&&&&&&&&&&&%///
// ////##&###///////////@/&... . ##//////////////(/@@@@@@@@@@@@@@@@@@( //% //%%@@@ &%[email protected]@@@@@@@@@@%&# %&%@@&&&&&&&&@@@@@@&&&&&&&&&&&&%//.
// //###(///**//////////#/...... .&&&&&&&. #/*/*////####/((/@@@@@@@@@@@@@@@@@@@/%@ //%%%@*(#@@#[email protected]@@@@@@@@@@@%,#,#@&&&&&&&&&@@@@@&&&&&&@@@@@&&&&&// /
// ,###(/////**///////////....... .&&@@@@@@@&&. ////########(/((%@@@@@@@@@@@@@@@@@@,@@.#/%%%%/@((/*[email protected]@@@@@@@@@&&&&&&@&&&&&&&@@@@@@&&&&@@@&@@@&&&&&///
// &###((////&&&&&&//////(@/........ @@%&.#######(@&&&&&&&&&&@@@@@@@@@@@@@@@@@@@% /%% ///// [email protected]@@@@@@@@&&&&&&&&&&&@@@@@@&&&&@@&&@&@&&&@&&*///
// @@&&#(/(&&&&&&@@@&&@////(#*,........ &%@@@@@@@@& [email protected]###@&&&&&&@&&&&&@&@@@@@@@@@@@@@@@@@@@%@// /// [email protected]&@&&&&&&&&&&&&&&@@@@@@@&&&@@&&@&@@&@&&&&////////.
// @@@@@#&&&&@@@@&&&/&&&&**/#(((,,.,,,,,,,#&&%%%&&&[email protected]##@&&&&&&&(((((((//@@@@@@@@@@@@@@@@@@@@@@/.//*@/////@@@///[email protected]@@&&&&&&&&@@@@@@@@@&&&&@@&@&&@&@&@&&///////
// @@@@@@#&&&@@#&&&//%&&&&/*/##//#,,,,,,,,,,,,,,,,,,.&##@&&&&@#(((((((&@@&&@@@@@@@@@@@@@@@@@&&%@ *//////////[email protected]@@@@@@@@@@@@@@@&&&&@@&@&@&&&&&&@////////
// @@#@@@@&&&&@##@&&&&&&&@#//@&&@#####,,,,,,,,,,,,,@//#&@&&&&(#(((@&&&&&&&&&@@@@@@@@@@@@@@@@@@@&&@ //////*.....................,,*@@@@@@@&&@@@&&&&@@&&&&&@&&&//////////
// @@@@@@@@@@@@@@&&&&&&&&&&&&&&&&&&&&####/(#########/#@@&&&&#((@&&&&&&&&@/@@@@@@@@@@@@@@@@@@@@@@@@ ////*......................,,,,,,@@&&&&&&@@@&&&&&&&&&&&&/////////////
// @@@@@&&@&&@&&&&&&&&&&&&@@@@@&&&@&&&&############@@&&&&%((@&&&&&@((((((@@@@@@@@@@@@@@@@@@&&&&&&, ///@%%%%%%####((((@%.....,,,,@@&&&&&&&&@@@@@@@@@@@@&&///////////%///
// ,,,,,,,,,,,*,......... @@@@@@@&&&&&&#######@@&&&&&@(((@&&&&&(////((@@@@@@@@@@@@@@@@@@@@@&&& // //%%&((**(((((/*,[email protected]@&&&&&&&&*******@%%%%%%%%/////%////(%%(/
// .,,,,,,,/,, ....,*... @@@@@@@@@&&&&@&&&&&&&&&&&(((((@@&&&&((/(/((/@@@@@@@@@@@@@@@@@@@@@#//////.//////*/////**[email protected]@&&&&&*****/////@&%%%%%%%%%///%%////%%%*/
// ,,,,,,,@,,**,,[email protected]&@@@@@@@@@@@&&&&&&&&&&@(((((((@@&&&@(((((((/@@@@@@@@@@@@@@@@@@@& /////////,//%...../*...........,,,,,******/////@@@%%%%%%%%%#/#%%%//%%%% /
// ,@,,,,,@,,,..&@%,[email protected]@@@@@@@@@@@@@@@@@@@&####(((((((@&&&&@(((////@@@@@@@@@@@@@@@@@#//#/////////%%//...................,.,,*****@@@@@&&##%%%%%%%%%%/%%%%%%%%%%
// @@@@@@@@@@@@@@@@@@@&&&&&##(((((((@@&&&&//////@%#####@@@@@@@@@@@///%%%%%%%%%%%%% /[email protected]@@@@@@*/@&&&&%%%%%%%%%%%%%%%%%%%%%%
// @@@@@@@@@@%%%%%%%%%@@&&&&@#((((((@@&&&@@/////@######&@@@@@@@@@@@@@@@@@@@@&&/&%%%%%@****,,....(@%%%@@@@@*(///***@&&&#%%%%%%#% %%%%%%%% %
// @@@@@@,%%%%%%%%%%//@@&&&&&#((((((@@@@@@////@@######%@@@@@@&@@##/#/(@@@@@@@@&&%%%%%%%%%%%%%%%%%%%%%@/////***.,.,@&&&&%#%##### %%%%%%. /
// *@,@@@# @@@,,/,... %%%%%%%@%%%%%%@((((#@@@@@#((@@@########@@@@&&@@@###/#/(////@@@@%%%%%#%%%%%%%%%%%/%%%%% //**.*,,.,..#&&&&%%%%&&##%%%%
// ,,,,,,. @@@@@@@#,,*,,.. .*%%%%%%%%%%%((,#@@@@@@@@@@@#######**@@@&&&@@&&&@####/(////***@@@@@&& #%%%( @**,,,......&&&&&%%%%%%####
// ,,,,,,,,[email protected]@@@@@@,,,**......%%%%%%%(%%#////@@###############@@@&&&&&&&&&@&@###((////////**@@@@& [email protected]&&&&&%%%%%%%##
// ,,*,,....,....*,/,,,,[email protected]@&&&@@%%/(#%//,#@@@@##########@@@&&&&@&&&&&&@@%##(((////////***//@@@# &[email protected]&&&&&%%%%%%###%
// @@,,*&,,,,,,,,,,,,,,,,[email protected]@&&&&&&@@&%///#//,@@@@@(#@(##@@@@@&&&&&&&&&&&@####(((((///////////// @@@ [email protected]&&&&&%%%%%#%####
// @@@@@@@@@@&&&@@@@@@@&&&&&&&&&&&&@&&&&#///(/.,@@@@@@@@@@@@@&&&&&&&&&&&&&&@####((((((////////////* &@ ...........&&&&&&%%%%%%%##@@@@@@@@
// @@@@@@@@@@@@@@&@@&&&&&&&&&&&&@&&&&&&##//(((,,@@@@@@@@@@&&&&&&&&&&&&&&&&@@#@@((@(((((///////////. @ (@@..........&&&&&&%%%%%%@@@@&@@@@@@@@@@@@@
// ,@@@@@@@@@@@@@@@&@&&&@@@@@@&&&&&@ #%//////,,@@@@@@@@&&&&&&&&&&&&&&&&&@@@@(##(#(#(&(((((((((((( /@@@@@@@@//%............&@@&&%%&@@@@@@@@@@@@@@@@@@@@@@@@@@@%
// @@@@@@@@@@@@@@@@&@&@&&, (%%//////(,@@@@@@@@&&&&&&&&&&&&&&&&&&&&&@(%#(#((##(#(((&@@@@@@@@@@@@@@@@@@///@[email protected]@@@@&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@&@&&@ /%/////////@@@@@@@@@&&&&&&&&&&&&&&&&&&&@@@%#%#@@@@@@@@@@@@@@@@@@@@@@@@@@@[email protected]@@@@@@&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&@@@@(
// @@@@@@@@@@@@@&@@ %%/////%////(@@@@@@@@&&&&&&&&&&&&&&&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// ,@@@@@@@@@@@@@ %#%///%##%&@@@@@@@@@@@@@@&&&&&&&&&&&&&@@@@@&@@@@@@@@@@@@@@@@@@@@@@@@@@@@&@@@@@@@@@&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@ &#%#%//%%%%%%@@@@@@@@@@@@@@@&&@@@@@&&&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&@@@@@@@@@@@@@@@@@@
// ,@@@@@@@ &%&&&&%&&&&&&& @@@@@@@@@@@@@@@@@@&&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@ &&&&&&&@@@@@@& @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%
// &&&&@@@@@@@@@ @@@@@&@&&&&&@&@@@@@@@@@@@@&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@[email protected]@.%. @@@@@[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&,@@.,(@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@% @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@... @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@&&&@@@@@@@@ ######@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ | January 18, 8:59:59 am PST
| uint256 public endPresaleDate = 1642525199; | 14,332,590 | [
1,
46,
304,
24335,
6549,
16,
1725,
30,
6162,
30,
6162,
2125,
453,
882,
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,
679,
12236,
5349,
1626,
273,
404,
1105,
2947,
2947,
19818,
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
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
import {IOracle} from "./gamma/interfaces/IOracle.sol";
import {IAddressBook} from "./gamma/interfaces/IAddressBook.sol";
import {OtokenInterface} from "./gamma/interfaces/OtokenInterface.sol";
import {ISwap, Types} from "./airswap/interfaces/ISwap.sol";
import {IFactory} from "./interfaces/IFactory.sol";
import {ERC20, IERC20} from "../oz/token/ERC20/ERC20.sol";
import {IERC1155} from "../oz/token/ERC1155/IERC1155.sol";
import {SafeERC20} from "../oz/token/ERC20/utils/SafeERC20.sol";
import {PausableUpgradeable} from "../oz/security/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "../oz/security/ReentrancyGuardUpgradeable.sol";
contract VaultComponents is PausableUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
error ClosedPermanently();
error WithdrawalWindowActive();
error oTokenNotCleared();
error Unauthorized();
error Invalid();
error Invalid_StrikeTooDeepITM();
error NotEnoughFunds();
error NotEnoughFunds_ReserveViolation();
error NotEnoughFunds_ObligatedFees();
error MaximumFundsReached();
error SettlementNotReady();
enum WaiverType {
ERC20,
ERC721,
ERC1155
}
struct Waiver {
mapping(uint256 => bool) isValidID;
uint256 minimumAmount;
WaiverType standard;
uint16 depositDeduction;
uint16 withdrawalDeduction;
}
/// @notice Tokens the manager can set to have fees reduced/waived
mapping(address => Waiver) public waiverTokens;
/// @notice Time in which the withdrawal window expires
uint256 public withdrawalWindowExpires;
/// @notice Length of time where the withdrawal window is active
uint256 public withdrawalWindowLength;
/// @notice Amount of collateral for the address already used for collateral
uint256 public collateralAmount;
/// @notice Maximum funds
uint256 public maximumAssets;
/// @notice Amount temporarily withheld for the round by premiums
uint256 public premiumsWithheld;
/// @notice Current active vault
uint256 internal currentVaultId;
/// @notice Obligated fees to the manager
uint256 public obligatedFees;
/// @notice Current reserves
uint256 public currentReserves;
/// @notice Fees to the protocol
uint256 public withheldProtocolFees;
/// @notice Address of Opyn's Gamma AddressBook contract
IAddressBook internal addressBook;
/// @notice Address of the factory
IFactory public factory;
/// @notice Address of the manager (admin)
address public manager;
/// @notice Address of the current oToken
address public oToken;
/// @notice Address of the underlying asset to trade
address public asset;
/// @notice Deposit fee
uint16 public depositFee;
/// @notice Take profit fee
uint16 public withdrawalFee;
/// @notice Early withdrawal penalty
uint16 public earlyWithdrawalPenalty;
/// @notice Performance fee (taken when options are sold)
uint16 public performanceFee;
/// @notice Withdrawal reserve percentage
uint16 public withdrawalReserve;
/// @notice Determines if the vault is closed permanently
bool public closedPermanently;
event OptionsMinted(uint256 collateralDeposited, address indexed newOtoken, uint256 vaultId);
event OptionsBurned(uint256 oTokensBurned);
event OptionsSold(uint256 amountSold, uint256 premiumReceived);
event Deposit(uint256 assetDeposited, uint256 vaultTokensMinted);
event Withdrawal(uint256 assetWithdrew, uint256 vaultTokensBurned);
event WithdrawalWindowActivated(uint256 closesAfter);
event ReservesEstablished(uint256 allocatedReserves);
event MaximumAssetsModified(uint256 newAUM);
event DepositFeeModified(uint16 newFee);
event WithdrawalFeeModified(uint16 newFee);
event EarlyWithdrawalPenalty(uint16 newFee);
event PerformanceFeeModified(uint16 newFee);
event WithdrawalReserveModified(uint16 newReserve);
event WaiverTokenModified(address token, uint16 depositDeduction, uint16 withdrawawlDeduction);
event VaultClosedPermanently();
modifier onlyManager {
_onlyManager();
_;
}
modifier ifNotClosed {
_ifNotClosed();
_;
}
/// @notice For emergency use
/// @dev Stops all activities on the vault (or reactivates them)
/// @param _val true to pause the vault, false to unpause the vault
function emergency(bool _val) external ifNotClosed onlyManager {
_val ? super._pause() : super._unpause();
}
/// @notice Changes the maximum allowed deposits under management
/// @dev Changes the maximumAssets to the new amount
/// @param _newValue new maximumAssets value
function adjustTheMaximumAssets(uint256 _newValue) external ifNotClosed onlyManager nonReentrant() whenNotPaused() {
if(_newValue < collateralAmount + IERC20(asset).balanceOf(address(this)))
revert Invalid();
maximumAssets = _newValue;
emit MaximumAssetsModified(_newValue);
}
/// @notice Close the vault permanently
/// @dev Manager closes the vault permanently, preventing new deposits and use of the vault
function closeVaultPermanently() external ifNotClosed onlyManager nonReentrant() whenNotPaused() {
if(oToken != address(0))
revert oTokenNotCleared();
closedPermanently = true;
IERC20(asset).safeTransfer(factory.admin(), withheldProtocolFees);
IERC20(asset).safeTransfer(msg.sender, obligatedFees);
withheldProtocolFees = 0;
obligatedFees = 0;
emit VaultClosedPermanently();
}
/// @notice Send withheld protocol fees to the factory's admin
/// @dev Any obligated fees for the protocol is sent to the factory's admin
function sendWithheldProtocolFees() external nonReentrant() whenNotPaused() {
IERC20(asset).safeTransfer(factory.admin(), withheldProtocolFees);
withheldProtocolFees = 0;
}
/// @notice Changes the deposit fee
/// @dev Changes the depositFee with two decimals of precision up to 50.00% (5000)
/// @param _newValue new depositFee with two decimals of precision
function adjustDepositFee(uint16 _newValue) external ifNotClosed onlyManager nonReentrant() whenNotPaused() {
if(_newValue > 5000)
revert Invalid();
depositFee = _newValue;
emit DepositFeeModified(_newValue);
}
/// @notice Changes the withdrawal fee
/// @dev Changes the withdrawalFee with two decimals of precision up to 33.33% (3333)
/// @param _newValue new withdrawalFee with two decimals of precision
function adjustWithdrawalFee(uint16 _newValue) external ifNotClosed onlyManager nonReentrant() whenNotPaused() {
if(_newValue > 3333)
revert Invalid();
withdrawalFee = _newValue;
emit WithdrawalFeeModified(_newValue);
}
/// @notice Changes the early withdrawal penalty
/// @dev Changes the earlyWithdrawalPenalty with two decimals of precision up to 33.33% (3333)
/// @param _newValue new earlyWithdrawalFee with two decimals of precision
function adjustEarlyWithdrawalPenalty(uint16 _newValue) external ifNotClosed onlyManager nonReentrant() whenNotPaused() {
if(_newValue > 3333)
revert Invalid();
earlyWithdrawalPenalty = _newValue;
emit EarlyWithdrawalPenalty(_newValue);
}
/// @notice Changes the performance fee
/// @dev Changes the performanceFee with two decimals of precision up to 50.00% (5000)
/// @param _newValue new performanceFee with two decimals of precision
function adjustPerformanceFee(uint16 _newValue) external ifNotClosed onlyManager nonReentrant() whenNotPaused() {
if(_newValue > 5000)
revert Invalid();
performanceFee = _newValue;
emit PerformanceFeeModified(_newValue);
}
/// @notice Changes the withdrawal reserve percentage
/// @dev Changes the withdrawalReserve with two decimals of precision up to 50.00% (5000)
/// @param _newValue new withdrawalReserve with two decimals of precision
function adjustWithdrawalReserve(uint16 _newValue) external ifNotClosed onlyManager nonReentrant() whenNotPaused() {
if(_newValue > 5000)
revert Invalid();
withdrawalReserve = _newValue;
emit WithdrawalReserveModified(_newValue);
}
/// @notice Changes the withdrawal window length
/// @dev Changes the withdrawalWindowLength in UNIX time
/// @param _newValue new withdrawalWindowLength period
function adjustWithdrawalWindowLength(uint256 _newValue) external ifNotClosed onlyManager nonReentrant() whenNotPaused() {
withdrawalWindowLength = _newValue;
}
/// @notice Adjusts the waiver for a specific token
/// @dev Replaces the waiver settings for a specific token with the specific parameters
/// @param _token Token address of the ERC20/ERC1155 eligible for waiver
/// @param _minimumAmount the minimum amount the user needs to hold in order for the waiver to be active
/// @param _depositDeduction Fee deduction against the deposit represented in % form with two decimals of precision (100.00% = 10000)
/// @param _withdrawalDeduction Fee deduction against the withdrawal represented in % form with two decimals of precision (100.00% = 10000)
/// @param _standard WaiverType enum determining what ERC standard the waiver is (IMPORTANT)
/// @param _idERC1155 If the standard is ERC1155, use this parameter to determine the ID necessary for the eligible waiver
/// @param _revokeId If the standard is ERC1155, use this parameter to determine if the ID needs to be revoked
function adjustWaiver(
address _token,
uint256 _minimumAmount,
uint256 _idERC1155,
uint16 _depositDeduction,
uint16 _withdrawalDeduction,
WaiverType _standard,
bool _revokeId
) external ifNotClosed onlyManager nonReentrant() whenNotPaused() {
if(_token == address(0))
revert Invalid();
Waiver storage waiver = waiverTokens[_token];
waiver.standard = _standard;
waiver.minimumAmount = _minimumAmount;
waiver.depositDeduction = _depositDeduction;
waiver.withdrawalDeduction = _withdrawalDeduction;
if(_standard == WaiverType.ERC1155) {
if(_revokeId) {
waiver.isValidID[_idERC1155] = false;
} else {
waiver.isValidID[_idERC1155] = true;
}
}
emit WaiverTokenModified(_token, _depositDeduction, _withdrawalDeduction);
}
/// @notice Allows the manager to collect fees
/// @dev Transfers all of the obligatedFees to the manager and sets it to zero
function sweepFees() external ifNotClosed onlyManager nonReentrant() whenNotPaused() {
IERC20(asset).safeTransfer(msg.sender, obligatedFees);
obligatedFees = 0;
}
/// @notice Allows the manager to collect random tokens sent to the contract
/// @dev Transfers all of the unrelated tokens to the manager
/// @param _token Address of the unrelated token that is not the oToken or the asset token
function sweepUnrelatedTokens(address _token) external ifNotClosed onlyManager nonReentrant() whenNotPaused() {
if(_token == oToken || _token == asset)
revert Invalid();
IERC20 unrelated = IERC20(_token);
unrelated.safeTransfer(msg.sender, unrelated.balanceOf(address(this)));
}
/// @notice Allows the manager to disperse obligatedFees to the depositors
/// @dev Transfers _amount to the vault and deducts against obligatedFees
/// @param _amount amount of the obligated fees (for the vault) to disperse to the vault itself
function disperseFees(uint256 _amount) external onlyManager nonReentrant() whenNotPaused() {
if(_amount > obligatedFees)
revert NotEnoughFunds_ObligatedFees();
obligatedFees -= _amount;
}
/// @notice Sells options via AirSwap
/// @dev Performs a full RFQ trade via AirSwap
/// @param _order A Types.Order struct that defines the AirSwap order (requires signature)
function _sellOptions(Types.Order memory _order) internal {
if(_order.sender.amount > IERC20(oToken).balanceOf(address(this)) || oToken == address(0))
revert Invalid();
address airswap = factory.airswapExchange();
// Approve
IERC20(oToken).approve(airswap, _order.sender.amount);
// Submit the order
ISwap(airswap).swap(_order);
// Fee calculation + withheldProtocolFees
obligatedFees += _percentMultiply(_order.signer.amount, performanceFee);
IERC20(asset).safeTransfer(address(factory), _percentMultiply(_order.signer.amount, factory.performanceFee()) + withheldProtocolFees);
withheldProtocolFees = 0;
// Withhold premiums temporarily
premiumsWithheld += _order.signer.amount;
emit OptionsSold(_order.sender.amount, _order.signer.amount);
}
/// @notice Checks if the vault is NOT closed permanently
/// @dev A modifier function to check the vault's closed status
function _ifNotClosed() internal view {
if(closedPermanently)
revert ClosedPermanently();
}
/// @notice Checks if the msg.sender is the manager of the vault
/// @dev A modifier function to check if msg.sender == manager
function _onlyManager() internal view {
if(msg.sender != manager)
revert Unauthorized();
}
/// @notice Calculates the ITM penalty for withdrawing early
/// @dev Internal function that calculates the penalty of an ITM withdrawal and penalizes against the user
/// @param _assetAmount is the amount of asset tokens being potentially withdrawn
/// @return adjustedBal is the balance after penalizing the user for an ITM withdrawal
function _calculatePenalty(uint256 _assetAmount) internal returns(uint256 adjustedBal) {
if(oToken == address(0) || (oToken != address(0) && block.timestamp >= OtokenInterface(oToken).expiryTimestamp()))
return _assetAmount;
uint256 strikePrice = OtokenInterface(oToken).strikePrice();
uint256 oraclePrice = IOracle(addressBook.getOracle()).getPrice(OtokenInterface(oToken).underlyingAsset());
uint16 percentageForUser = 10000;
if(OtokenInterface(oToken).isPut() && strikePrice > oraclePrice) {
percentageForUser = uint16(
(10e22 * oraclePrice / strikePrice)/10e18
);
} else if(oraclePrice > strikePrice) {
percentageForUser = uint16(
(10e22 * strikePrice / oraclePrice)/10e18
);
}
adjustedBal = _percentMultiply(_assetAmount, percentageForUser - earlyWithdrawalPenalty);
premiumsWithheld += (_assetAmount - adjustedBal);
}
/// @notice Normalizes a value to the requested decimals
/// @dev Normalizes a value from its current decimal to the requested amount of decimals
/// @param _valueToNormalize the value to normalize
/// @param _valueDecimal the value's current amount of decimals
/// @param _normalDecimals the new value's amount of decimals
/// @return Normalized value
function _normalize(
uint256 _valueToNormalize,
uint256 _valueDecimal,
uint256 _normalDecimals
) internal pure returns (uint256) {
int256 decimalDiff = int256(_valueDecimal) - int256(_normalDecimals);
if(decimalDiff > 0) {
return _valueToNormalize / (10**uint256(decimalDiff));
} else if(decimalDiff < 0) {
return _valueToNormalize * 10**uint256(-decimalDiff);
}
return _valueToNormalize;
}
/// @notice Checks if the withdrawal window is active
/// @dev A withdrawal window check that may either revert or return the status without revert
/// @return isActive true if the withdrawal window is open, otherwise false
function _withdrawalWindowCheck() internal view returns(bool isActive) {
return block.timestamp < withdrawalWindowExpires;
}
/// @notice Multiplies a value by a percentage
/// @dev A pure function to multiply a value by a percentage
/// @param _val value to multiply against the percentage
/// @param _percent uint16 with two decimals of precision representing the percentage
/// @return The product of the value * percentage
function _percentMultiply(uint256 _val, uint16 _percent) internal pure returns(uint256) {
return _val * _percent / 10000;
}
/// @notice Calculates the fees with waiver
/// @dev Calculation for fees and determining if a waiver is active/eligible
/// @param _amount Amount passed to determine the fees for the protocol and or vault
/// @param _protocolFee Percentage with two decimals of precision for the protocol fee
/// @param _vaultFee Percentage with two decimals of precision for the vault fees
/// @param _waiver Address of the waiver (if msg.sender is attempting to discount)
/// @param _idERC1155 If the waiver is an ERC1155, an ID must be passed to properly grab msg.sender's balance
/// @param _isDeposit Boolean to determine which fee to use to assist with the deduction
/// @return protocolFees The protocol fees
/// @return vaultFees The vault fees
function _calculateFees(
uint256 _amount,
uint16 _protocolFee,
uint16 _vaultFee,
address _waiver,
uint256 _idERC1155,
bool _isDeposit
) internal view returns(uint256 protocolFees, uint256 vaultFees) {
if(_waiver != address(0)) {
Waiver storage waiver = waiverTokens[_waiver];
uint16 whichDeduction = _isDeposit ? waiver.depositDeduction : waiver.withdrawalDeduction;
if(whichDeduction > _vaultFee) // prevent underflow
whichDeduction = _vaultFee;
if(waiver.standard != WaiverType.ERC1155) {
if(IERC20(_waiver).balanceOf(msg.sender) >= waiver.minimumAmount) {
_vaultFee -= whichDeduction;
}
} else if(waiver.standard == WaiverType.ERC1155 && waiver.isValidID[_idERC1155]) {
if(IERC1155(_waiver).balanceOf(msg.sender, _idERC1155) >= waiver.minimumAmount) {
_vaultFee -= whichDeduction;
}
}
}
protocolFees = _percentMultiply(_amount, _protocolFee);
vaultFees = _percentMultiply(_amount, _vaultFee);
}
} | @notice Address of the underlying asset to trade | address public asset;
| 5,507,657 | [
1,
1887,
434,
326,
6808,
3310,
358,
18542,
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,
1758,
1071,
3310,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2021 IndexCooperative
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";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol";
import { BaseAdapter } from "../lib/BaseAdapter.sol";
import { IBaseManager } from "../interfaces/IBaseManager.sol";
import { IGeneralIndexModule } from "../interfaces/IGeneralIndexModule.sol";
import { ISetToken } from "../interfaces/ISetToken.sol";
/**
* @title GIMExtension
* @author Set Protocol
*
* Smart contract manager extension that acts as a pass-through contract for interacting with GeneralIndexModule.
* All functions are only callable by operator. startRebalance() on GIM maps to startRebalanceWithUnits on
* GIMExtension.
*/
contract GIMExtension is BaseAdapter {
using AddressArrayUtils for address[];
using SafeMath for uint256;
/* ============ State Variables ============ */
ISetToken public setToken;
IGeneralIndexModule public generalIndexModule; // GIM
/* ============ Constructor ============ */
constructor(IBaseManager _manager, IGeneralIndexModule _generalIndexModule) public BaseAdapter(_manager) {
generalIndexModule = _generalIndexModule;
setToken = manager.setToken();
}
/* ============ External Functions ============ */
/**
* ONLY OPERATOR: Submits a startRebalance call to GeneralIndexModule. Uses internal function so that this contract can be inherited and
* custom startRebalance logic can be added on top. Components array is sorted in new and old components arrays in order to conform to
* startRebalance interface. See GIM for function specific restrictions.
* @param _components Array of components involved in rebalance inclusive of components being removed from set (targetUnit = 0)
* @param _targetUnits Array of target units at end of rebalance, maps to same index of _components array
* @param _positionMultiplier Position multiplier when target units were calculated, needed in order to adjust target units if fees accrued
*/
function startRebalanceWithUnits(
address[] calldata _components,
uint256[] calldata _targetUnits,
uint256 _positionMultiplier
)
external
onlyOperator
{
(
address[] memory newComponents,
uint256[] memory newComponentsTargetUnits,
uint256[] memory oldComponentsTargetUnits
) = _sortNewAndOldComponents(_components, _targetUnits);
_startRebalance(newComponents, newComponentsTargetUnits, oldComponentsTargetUnits, _positionMultiplier);
}
/**
* ONLY OPERATOR: Submits a setTradeMaximums call to GeneralIndexModule. See GIM for function specific restrictions.
*
* @param _components Array of components
* @param _tradeMaximums Array of trade maximums mapping to correct component
*/
function setTradeMaximums(
address[] memory _components,
uint256[] memory _tradeMaximums
)
external
onlyOperator
{
bytes memory callData = abi.encodeWithSelector(
IGeneralIndexModule.setTradeMaximums.selector,
setToken,
_components,
_tradeMaximums
);
invokeManager(address(generalIndexModule), callData);
}
/**
* ONLY OPERATOR: Submits a setExchanges call to GeneralIndexModule. See GIM for function specific restrictions.
*
* @param _components Array of components
* @param _exchangeNames Array of exchange names mapping to correct component
*/
function setExchanges(
address[] memory _components,
string[] memory _exchangeNames
)
external
onlyOperator
{
bytes memory callData = abi.encodeWithSelector(
IGeneralIndexModule.setExchanges.selector,
setToken,
_components,
_exchangeNames
);
invokeManager(address(generalIndexModule), callData);
}
/**
* ONLY OPERATOR: Submits a setCoolOffPeriods call to GeneralIndexModule. See GIM for function specific restrictions.
*
* @param _components Array of components
* @param _coolOffPeriods Array of cool off periods to correct component
*/
function setCoolOffPeriods(
address[] memory _components,
uint256[] memory _coolOffPeriods
)
external
onlyOperator
{
bytes memory callData = abi.encodeWithSelector(
IGeneralIndexModule.setCoolOffPeriods.selector,
setToken,
_components,
_coolOffPeriods
);
invokeManager(address(generalIndexModule), callData);
}
/**
* ONLY OPERATOR: Submits a setExchangeData call to GeneralIndexModule. See GIM for function specific restrictions.
*
* @param _components Array of components
* @param _exchangeData Array of exchange specific arbitrary bytes data
*/
function setExchangeData(
address[] memory _components,
bytes[] memory _exchangeData
)
external
onlyOperator
{
bytes memory callData = abi.encodeWithSelector(
IGeneralIndexModule.setExchangeData.selector,
setToken,
_components,
_exchangeData
);
invokeManager(address(generalIndexModule), callData);
}
/**
* ONLY OPERATOR: Submits a setRaiseTargetPercentage call to GeneralIndexModule. See GIM for function specific restrictions.
*
* @param _raiseTargetPercentage Amount to raise all component's unit targets by (in precise units)
*/
function setRaiseTargetPercentage(uint256 _raiseTargetPercentage) external onlyOperator {
bytes memory callData = abi.encodeWithSelector(
IGeneralIndexModule.setRaiseTargetPercentage.selector,
setToken,
_raiseTargetPercentage
);
invokeManager(address(generalIndexModule), callData);
}
/**
* ONLY OPERATOR: Submits a setTraderStatus call to GeneralIndexModule. See GIM for function specific restrictions.
*
* @param _traders Array trader addresses to toggle status
* @param _statuses Booleans indicating if matching trader can trade
*/
function setTraderStatus(
address[] memory _traders,
bool[] memory _statuses
)
external
onlyOperator
{
bytes memory callData = abi.encodeWithSelector(
IGeneralIndexModule.setTraderStatus.selector,
setToken,
_traders,
_statuses
);
invokeManager(address(generalIndexModule), callData);
}
/**
* ONLY OPERATOR: Submits a setAnyoneTrade call to GeneralIndexModule. See GIM for function specific restrictions.
*
* @param _status Boolean indicating if anyone can call trade
*/
function setAnyoneTrade(bool _status) external onlyOperator {
bytes memory callData = abi.encodeWithSelector(
IGeneralIndexModule.setAnyoneTrade.selector,
setToken,
_status
);
invokeManager(address(generalIndexModule), callData);
}
/**
* ONLY OPERATOR: Submits a initialize call to GeneralIndexModule. See GIM for function specific restrictions.
*/
function initialize() external onlyOperator {
bytes memory callData = abi.encodeWithSelector(
IGeneralIndexModule.initialize.selector,
setToken
);
invokeManager(address(generalIndexModule), callData);
}
/* ============ Internal Functions ============ */
/**
* Internal function that creates calldata and submits startRebalance call to GeneralIndexModule.
*
* @param _newComponents Array of new components to add to allocation
* @param _newComponentsTargetUnits Array of target units at end of rebalance for new components, maps to same index of _newComponents array
* @param _oldComponentsTargetUnits Array of target units at end of rebalance for old component, maps to same index of
* _setToken.getComponents() array, if component being removed set to 0.
* @param _positionMultiplier Position multiplier when target units were calculated, needed in order to adjust target units
* if fees accrued
*/
function _startRebalance(
address[] memory _newComponents,
uint256[] memory _newComponentsTargetUnits,
uint256[] memory _oldComponentsTargetUnits,
uint256 _positionMultiplier
)
internal
{
bytes memory callData = abi.encodeWithSelector(
IGeneralIndexModule.startRebalance.selector,
setToken,
_newComponents,
_newComponentsTargetUnits,
_oldComponentsTargetUnits,
_positionMultiplier
);
invokeManager(address(generalIndexModule), callData);
}
/**
* Internal function that sorts components into old and new components and builds the requisite target unit arrays. Old components target units
* MUST maintain the order of the components array on the SetToken. The _components array MUST contain an entry for all current components even if
* component is being removed (targetUnit = 0). This is validated implicitly by calculating the amount of new components that would be added as
* implied by the array lengths, if more than the expected amount of new components are added then it implies an old component is missing.
*
* @param _components Array of components involved in rebalance inclusive of components being removed from set (targetUnit = 0)
* @param _targetUnits Array of target units at end of rebalance, maps to same index of _components array
*/
function _sortNewAndOldComponents(
address[] memory _components,
uint256[] memory _targetUnits
)
internal
view
returns (address[] memory, uint256[] memory, uint256[] memory)
{
address[] memory currentComponents = setToken.getComponents();
uint256 currentSetComponentsLength = currentComponents.length;
uint256 rebalanceComponentsLength = _components.length;
require(rebalanceComponentsLength >= currentSetComponentsLength, "Components array must be equal or longer than current components");
// We assume that there is an entry for each old component regardless of if it's 0, so any additional components in the array
// must be added as a new component. Hence we can declare the length of the new components array as the difference between
// rebalanceComponentsLength and currentSetComponentsLength
uint256[] memory oldComponentsTargetUnits = new uint256[](currentSetComponentsLength);
address[] memory newComponents = new address[](rebalanceComponentsLength.sub(currentSetComponentsLength));
uint256[] memory newTargetUnits = new uint256[](rebalanceComponentsLength.sub(currentSetComponentsLength));
uint256 newCounter; // Count amount of components added to newComponents array to add new components to next index
for (uint256 i = 0; i < rebalanceComponentsLength; i++) {
address component = _components[i];
(uint256 index, bool isIn) = currentComponents.indexOf(component);
if (isIn) {
oldComponentsTargetUnits[index] = _targetUnits[i]; // Use index in order to map to correct component in currentComponents array
} else {
require(newCounter < newComponents.length, "Unexpected new component added");
newComponents[newCounter] = component;
newTargetUnits[newCounter] = _targetUnits[i];
newCounter = newCounter.add(1);
}
}
return (newComponents, newTargetUnits, oldComponentsTargetUnits);
}
}
// 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;
/**
* @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;
}
}
/*
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;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*
* CHANGELOG:
* - 4/27/21: Added validatePairsWithArray methods
*/
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");
}
}
/*
Copyright 2021 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.
*/
pragma solidity 0.6.10;
import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol";
import { IBaseManager } from "../interfaces/IBaseManager.sol";
/**
* @title BaseAdapter
* @author Set Protocol
*
* Abstract class that houses common adapter-related state and functions.
*/
abstract contract BaseAdapter {
using AddressArrayUtils for address[];
/* ============ Events ============ */
event CallerStatusUpdated(address indexed _caller, bool _status);
event AnyoneCallableUpdated(bool indexed _status);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == manager.operator(), "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == manager.methodologist(), "Must be methodologist");
_;
}
/**
* Throws if caller is a contract, can be used to stop flash loan and sandwich attacks
*/
modifier onlyEOA() {
require(msg.sender == tx.origin, "Caller must be EOA Address");
_;
}
/**
* Throws if not allowed caller
*/
modifier onlyAllowedCaller(address _caller) {
require(isAllowedCaller(_caller), "Address not permitted to call");
_;
}
/* ============ State Variables ============ */
// Instance of manager contract
IBaseManager public manager;
// Boolean indicating if anyone can call function
bool public anyoneCallable;
// Mapping of addresses allowed to call function
mapping(address => bool) public callAllowList;
/* ============ Constructor ============ */
constructor(IBaseManager _manager) public { manager = _manager; }
/* ============ External Functions ============ */
/**
* OPERATOR ONLY: Toggle ability for passed addresses to call only allowed caller functions
*
* @param _callers Array of caller addresses to toggle status
* @param _statuses Array of statuses for each caller
*/
function updateCallerStatus(address[] calldata _callers, bool[] calldata _statuses) external onlyOperator {
require(_callers.length == _statuses.length, "Array length mismatch");
require(_callers.length > 0, "Array length must be > 0");
require(!_callers.hasDuplicate(), "Cannot duplicate callers");
for (uint256 i = 0; i < _callers.length; i++) {
address caller = _callers[i];
bool status = _statuses[i];
callAllowList[caller] = status;
emit CallerStatusUpdated(caller, status);
}
}
/**
* OPERATOR ONLY: Toggle whether anyone can call function, bypassing the callAllowlist
*
* @param _status Boolean indicating whether to allow anyone call
*/
function updateAnyoneCallable(bool _status) external onlyOperator {
anyoneCallable = _status;
emit AnyoneCallableUpdated(_status);
}
/* ============ Internal Functions ============ */
/**
* Invoke manager to transfer tokens from manager to other contract.
*
* @param _token Token being transferred from manager contract
* @param _amount Amount of token being transferred
*/
function invokeManagerTransfer(address _token, address _destination, uint256 _amount) internal {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _destination, _amount);
invokeManager(_token, callData);
}
/**
* Invoke call from manager
*
* @param _module Module to interact with
* @param _encoded Encoded byte data
*/
function invokeManager(address _module, bytes memory _encoded) internal {
manager.interactManager(_module, _encoded);
}
/**
* Determine if passed address is allowed to call function. If anyoneCallable set to true anyone can call otherwise needs to be approved.
*
* return bool Boolean indicating if allowed caller
*/
function isAllowedCaller(address _caller) internal view virtual returns (bool) {
return anyoneCallable || callAllowList[_caller];
}
}
/*
Copyright 2021 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.
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ISetToken } from "./ISetToken.sol";
interface IBaseManager {
function setToken() external returns(ISetToken);
function methodologist() external returns(address);
function operator() external returns(address);
function interactManager(address _module, bytes calldata _encoded) external;
}
/*
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 { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ISetToken } from "./ISetToken.sol";
interface IGeneralIndexModule {
function startRebalance(
ISetToken _setToken,
address[] calldata _newComponents,
uint256[] calldata _newComponentsTargetUnits,
uint256[] calldata _oldComponentsTargetUnits,
uint256 _positionMultiplier
)
external;
function trade(
ISetToken _setToken,
IERC20 _component,
uint256 _ethQuantityLimit
)
external;
function tradeRemainingWETH(
ISetToken _setToken,
IERC20 _component,
uint256 _minComponentReceived
)
external;
function raiseAssetTargets(ISetToken _setToken) external;
function setTradeMaximums(
ISetToken _setToken,
address[] memory _components,
uint256[] memory _tradeMaximums
)
external;
function setExchanges(
ISetToken _setToken,
address[] memory _components,
string[] memory _exchangeNames
)
external;
function setCoolOffPeriods(
ISetToken _setToken,
address[] memory _components,
uint256[] memory _coolOffPeriods
)
external;
function setExchangeData(
ISetToken _setToken,
address[] memory _components,
bytes[] memory _exchangeData
)
external;
function setRaiseTargetPercentage(ISetToken _setToken, uint256 _raiseTargetPercentage) external;
function setTraderStatus(
ISetToken _setToken,
address[] memory _traders,
bool[] memory _statuses
)
external;
function setAnyoneTrade(ISetToken _setToken, bool _status) external;
function initialize(ISetToken _setToken) external;
}
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken 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 SetToken
* @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);
}
| * @title BaseAdapter @author Set Protocol Abstract class that houses common adapter-related state and functions./ | abstract contract BaseAdapter {
using AddressArrayUtils for address[];
event CallerStatusUpdated(address indexed _caller, bool _status);
event AnyoneCallableUpdated(bool indexed _status);
Copyright 2021 Set Labs Inc.
import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol";
import { IBaseManager } from "../interfaces/IBaseManager.sol";
modifier onlyOperator() {
require(msg.sender == manager.operator(), "Must be operator");
_;
}
modifier onlyMethodologist() {
require(msg.sender == manager.methodologist(), "Must be methodologist");
_;
}
modifier onlyEOA() {
require(msg.sender == tx.origin, "Caller must be EOA Address");
_;
}
modifier onlyAllowedCaller(address _caller) {
require(isAllowedCaller(_caller), "Address not permitted to call");
_;
}
IBaseManager public manager;
bool public anyoneCallable;
mapping(address => bool) public callAllowList;
constructor(IBaseManager _manager) public { manager = _manager; }
function updateCallerStatus(address[] calldata _callers, bool[] calldata _statuses) external onlyOperator {
require(_callers.length == _statuses.length, "Array length mismatch");
require(_callers.length > 0, "Array length must be > 0");
require(!_callers.hasDuplicate(), "Cannot duplicate callers");
for (uint256 i = 0; i < _callers.length; i++) {
address caller = _callers[i];
bool status = _statuses[i];
callAllowList[caller] = status;
emit CallerStatusUpdated(caller, status);
}
}
function updateCallerStatus(address[] calldata _callers, bool[] calldata _statuses) external onlyOperator {
require(_callers.length == _statuses.length, "Array length mismatch");
require(_callers.length > 0, "Array length must be > 0");
require(!_callers.hasDuplicate(), "Cannot duplicate callers");
for (uint256 i = 0; i < _callers.length; i++) {
address caller = _callers[i];
bool status = _statuses[i];
callAllowList[caller] = status;
emit CallerStatusUpdated(caller, status);
}
}
function updateAnyoneCallable(bool _status) external onlyOperator {
anyoneCallable = _status;
emit AnyoneCallableUpdated(_status);
}
function invokeManagerTransfer(address _token, address _destination, uint256 _amount) internal {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _destination, _amount);
invokeManager(_token, callData);
}
function invokeManager(address _module, bytes memory _encoded) internal {
manager.interactManager(_module, _encoded);
}
function isAllowedCaller(address _caller) internal view virtual returns (bool) {
return anyoneCallable || callAllowList[_caller];
}
}
| 474,019 | [
1,
2171,
4216,
225,
1000,
4547,
4115,
667,
716,
366,
1481,
281,
2975,
4516,
17,
9243,
919,
471,
4186,
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
] | [
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,
17801,
6835,
3360,
4216,
288,
203,
565,
1450,
5267,
1076,
1989,
364,
1758,
8526,
31,
203,
203,
203,
565,
871,
20646,
1482,
7381,
12,
2867,
8808,
389,
16140,
16,
1426,
389,
2327,
1769,
203,
565,
871,
5502,
476,
11452,
7381,
12,
6430,
8808,
389,
2327,
1769,
203,
203,
203,
565,
25417,
26599,
21,
1000,
511,
5113,
15090,
18,
203,
203,
5666,
288,
5267,
1076,
1989,
289,
628,
315,
6216,
2941,
19,
1887,
1076,
1989,
18,
18281,
14432,
203,
5666,
288,
467,
2171,
1318,
289,
628,
315,
6216,
15898,
19,
45,
2171,
1318,
18,
18281,
14432,
203,
565,
9606,
1338,
5592,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3301,
18,
9497,
9334,
315,
10136,
506,
3726,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
1305,
3966,
376,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3301,
18,
2039,
3966,
376,
9334,
315,
10136,
506,
707,
3966,
376,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
41,
28202,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
2229,
18,
10012,
16,
315,
11095,
1297,
506,
512,
28202,
5267,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5042,
11095,
12,
2867,
389,
16140,
13,
288,
203,
3639,
2583,
12,
291,
5042,
11095,
24899,
16140,
3631,
315,
1887,
486,
15498,
358,
745,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
565,
467,
2171,
1318,
1071,
3301,
31,
203,
565,
1426,
2
] |
// 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";
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 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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_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.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: 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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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: MIT
pragma solidity 0.8.3;
interface IAddressList {
function add(address a) external returns (bool);
function remove(address a) external returns (bool);
function get(address a) external view returns (uint256);
function contains(address a) external view returns (bool);
function length() external view returns (uint256);
function grantRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IAddressListFactory {
function ours(address a) external view returns (bool);
function listCount() external view returns (uint256);
function listAt(uint256 idx) external view returns (address);
function createList() external returns (address listaddr);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/* solhint-disable func-name-mixedcase */
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
interface ISwapManager {
event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period);
function N_DEX() external view returns (uint256);
function ROUTERS(uint256 i) external view returns (IUniswapV2Router02);
function bestOutputFixedInput(
address _from,
address _to,
uint256 _amountIn
)
external
view
returns (
address[] memory path,
uint256 amountOut,
uint256 rIdx
);
function bestPathFixedInput(
address _from,
address _to,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function bestInputFixedOutput(
address _from,
address _to,
uint256 _amountOut
)
external
view
returns (
address[] memory path,
uint256 amountIn,
uint256 rIdx
);
function bestPathFixedOutput(
address _from,
address _to,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function safeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function safeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function comparePathsFixedInput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function comparePathsFixedOutput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function ours(address a) external view returns (bool);
function oracleCount() external view returns (uint256);
function oracleAt(uint256 idx) external view returns (address);
function getOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external view returns (address);
function createOrUpdateOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external returns (address oracleAddr);
function consultForFree(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
) external view returns (uint256 amountOut, uint256 lastUpdatedAt);
/// get the data we want and pay the gas to update
function consult(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
)
external
returns (
uint256 amountOut,
uint256 lastUpdatedAt,
bool updated
);
function updateOracles() external returns (uint256 updated, uint256 expected);
function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface CToken {
function accrueInterest() external returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function mint() external payable; // For ETH
function mint(uint256 mintAmount) external returns (uint256); // For ERC20
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function transfer(address user, uint256 amount) external returns (bool);
function transferFrom(
address owner,
address user,
uint256 amount
) external returns (bool);
function balanceOf(address owner) external view returns (uint256);
}
interface Comptroller {
function claimComp(address holder, address[] memory) external;
function compAccrued(address holder) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface TokenLike is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface ICollateralManager {
function addGemJoin(address[] calldata _gemJoins) external;
function borrow(uint256 _amount) external;
function createVault(bytes32 _collateralType) external returns (uint256 _vaultNum);
function depositCollateral(uint256 _amount) external;
function payback(uint256 _amount) external;
function transferVaultOwnership(address _newOwner) external;
function withdrawCollateral(uint256 _amount) external;
function getVaultBalance(address _vaultOwner) external view returns (uint256 collateralLocked);
function getVaultDebt(address _vaultOwner) external view returns (uint256 daiDebt);
function getVaultInfo(address _vaultOwner)
external
view
returns (
uint256 collateralLocked,
uint256 daiDebt,
uint256 collateralUsdRate,
uint256 collateralRatio,
uint256 minimumDebt
);
function mcdManager() external view returns (address);
function vaultNum(address _vaultOwner) external view returns (uint256 _vaultNum);
function whatWouldWithdrawDo(address _vaultOwner, uint256 _amount)
external
view
returns (
uint256 collateralLocked,
uint256 daiDebt,
uint256 collateralUsdRate,
uint256 collateralRatio,
uint256 minimumDebt
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IStrategy {
function rebalance() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function feeCollector() external view returns (address);
function isReservedToken(address _token) external view returns (bool);
function migrate(address _newStrategy) external;
function token() external view returns (address);
function totalValue() external view returns (uint256);
function pool() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../bloq/IAddressList.sol";
interface IVesperPool is IERC20 {
function deposit() external payable;
function deposit(uint256 _share) external;
function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool);
function excessDebt(address _strategy) external view returns (uint256);
function permit(
address,
address,
uint256,
uint256,
uint8,
bytes32,
bytes32
) external;
function poolRewards() external returns (address);
function reportEarning(
uint256 _profit,
uint256 _loss,
uint256 _payback
) external;
function reportLoss(uint256 _loss) external;
function resetApproval() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function withdrawETH(uint256 _amount) external;
function whitelistedWithdraw(uint256 _amount) external;
function governor() external view returns (address);
function keepers() external view returns (IAddressList);
function maintainers() external view returns (IAddressList);
function feeCollector() external view returns (address);
function pricePerShare() external view returns (uint256);
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
);
function stopEverything() external view returns (bool);
function token() external view returns (IERC20);
function tokensHere() external view returns (uint256);
function totalDebtOf(address _strategy) external view returns (uint256);
function totalValue() external view returns (uint256);
function withdrawFee() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "../interfaces/bloq/ISwapManager.sol";
import "../interfaces/bloq/IAddressList.sol";
import "../interfaces/bloq/IAddressListFactory.sol";
import "../interfaces/vesper/IStrategy.sol";
import "../interfaces/vesper/IVesperPool.sol";
abstract contract Strategy is IStrategy, Context {
using SafeERC20 for IERC20;
IERC20 public immutable collateralToken;
address public immutable receiptToken;
address public immutable override pool;
IAddressList public keepers;
address public override feeCollector;
ISwapManager public swapManager;
address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 internal constant MAX_UINT_VALUE = type(uint256).max;
event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector);
event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager);
constructor(
address _pool,
address _swapManager,
address _receiptToken
) {
require(_pool != address(0), "pool-address-is-zero");
require(_swapManager != address(0), "sm-address-is-zero");
swapManager = ISwapManager(_swapManager);
pool = _pool;
collateralToken = IERC20(IVesperPool(_pool).token());
receiptToken = _receiptToken;
}
modifier onlyGovernor {
require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor");
_;
}
modifier onlyKeeper() {
require(keepers.contains(_msgSender()), "caller-is-not-a-keeper");
_;
}
modifier onlyPool() {
require(_msgSender() == pool, "caller-is-not-vesper-pool");
_;
}
/**
* @notice Add given address in keepers list.
* @param _keeperAddress keeper address to add.
*/
function addKeeper(address _keeperAddress) external onlyGovernor {
require(keepers.add(_keeperAddress), "add-keeper-failed");
}
/**
* @notice Create keeper list
* NOTE: Any function with onlyKeeper modifier will not work until this function is called.
* NOTE: Due to gas constraint this function cannot be called in constructor.
* @param _addressListFactory To support same code in eth side chain, user _addressListFactory as param
* ethereum- 0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3
* polygon-0xD10D5696A350D65A9AA15FE8B258caB4ab1bF291
*/
function init(address _addressListFactory) external onlyGovernor {
require(address(keepers) == address(0), "keeper-list-already-created");
// Prepare keeper list
IAddressListFactory _factory = IAddressListFactory(_addressListFactory);
keepers = IAddressList(_factory.createList());
require(keepers.add(_msgSender()), "add-keeper-failed");
}
/**
* @notice Migrate all asset and vault ownership,if any, to new strategy
* @dev _beforeMigration hook can be implemented in child strategy to do extra steps.
* @param _newStrategy Address of new strategy
*/
function migrate(address _newStrategy) external virtual override onlyPool {
require(_newStrategy != address(0), "new-strategy-address-is-zero");
require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy");
_beforeMigration(_newStrategy);
IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this)));
collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this)));
}
/**
* @notice Remove given address from keepers list.
* @param _keeperAddress keeper address to remove.
*/
function removeKeeper(address _keeperAddress) external onlyGovernor {
require(keepers.remove(_keeperAddress), "remove-keeper-failed");
}
/**
* @notice Update fee collector
* @param _feeCollector fee collector address
*/
function updateFeeCollector(address _feeCollector) external onlyGovernor {
require(_feeCollector != address(0), "fee-collector-address-is-zero");
require(_feeCollector != feeCollector, "fee-collector-is-same");
emit UpdatedFeeCollector(feeCollector, _feeCollector);
feeCollector = _feeCollector;
}
/**
* @notice Update swap manager address
* @param _swapManager swap manager address
*/
function updateSwapManager(address _swapManager) external onlyGovernor {
require(_swapManager != address(0), "sm-address-is-zero");
require(_swapManager != address(swapManager), "sm-is-same");
emit UpdatedSwapManager(address(swapManager), _swapManager);
swapManager = ISwapManager(_swapManager);
}
/// @dev Approve all required tokens
function approveToken() external onlyKeeper {
_approveToken(0);
_approveToken(MAX_UINT_VALUE);
}
function setupOracles() external onlyKeeper {
_setupOracles();
}
/**
* @dev Withdraw collateral token from lending pool.
* @param _amount Amount of collateral token
*/
function withdraw(uint256 _amount) external override onlyPool {
_withdraw(_amount);
}
/**
* @dev Rebalance profit, loss and investment of this strategy
*/
function rebalance() external virtual override onlyKeeper {
(uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport();
IVesperPool(pool).reportEarning(_profit, _loss, _payback);
_reinvest();
}
/**
* @dev sweep given token to feeCollector of strategy
* @param _fromToken token address to sweep
*/
function sweepERC20(address _fromToken) external override onlyKeeper {
require(feeCollector != address(0), "fee-collector-not-set");
require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral");
require(!isReservedToken(_fromToken), "not-allowed-to-sweep");
if (_fromToken == ETH) {
Address.sendValue(payable(feeCollector), address(this).balance);
} else {
uint256 _amount = IERC20(_fromToken).balanceOf(address(this));
IERC20(_fromToken).safeTransfer(feeCollector, _amount);
}
}
/// @notice Returns address of token correspond to collateral token
function token() external view override returns (address) {
return receiptToken;
}
/// @dev Convert from 18 decimals to token defined decimals. Default no conversion.
function convertFrom18(uint256 amount) public pure virtual returns (uint256) {
return amount;
}
/**
* @notice Calculate total value of asset under management
* @dev Report total value in collateral token
*/
function totalValue() external view virtual override returns (uint256 _value);
/// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep.
function isReservedToken(address _token) public view virtual override returns (bool);
/**
* @notice some strategy may want to prepare before doing migration.
Example In Maker old strategy want to give vault ownership to new strategy
* @param _newStrategy .
*/
function _beforeMigration(address _newStrategy) internal virtual;
/**
* @notice Generate report for current profit and loss. Also liquidate asset to payback
* excess debt, if any.
* @return _profit Calculate any realized profit and convert it to collateral, if not already.
* @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token.
* @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt.
*/
function _generateReport()
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _payback
)
{
uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this));
uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this));
_profit = _realizeProfit(_totalDebt);
_loss = _realizeLoss(_totalDebt);
_payback = _liquidate(_excessDebt);
}
/**
* @notice Safe swap via Uniswap / Sushiswap (better rate of the two)
* @dev There are many scenarios when token swap via Uniswap can fail, so this
* method will wrap Uniswap call in a 'try catch' to make it fail safe.
* @param _from address of from token
* @param _to address of to token
* @param _amountIn Amount to be swapped
* @param _minAmountOut minimum acceptable return amount
*/
function _safeSwap(
address _from,
address _to,
uint256 _amountIn,
uint256 _minAmountOut
) internal {
(address[] memory path, uint256 amountOut, uint256 rIdx) =
swapManager.bestOutputFixedInput(_from, _to, _amountIn);
if (_minAmountOut == 0) _minAmountOut = 1;
if (amountOut != 0) {
swapManager.ROUTERS(rIdx).swapExactTokensForTokens(
_amountIn,
_minAmountOut,
path,
address(this),
block.timestamp
);
}
}
// These methods can be implemented by the inheriring strategy.
/* solhint-disable no-empty-blocks */
function _claimRewardsAndConvertTo(address _toToken) internal virtual {}
/**
* @notice Set up any oracles that are needed for this strategy.
*/
function _setupOracles() internal virtual {}
/* solhint-enable */
// These methods must be implemented by the inheriting strategy
function _withdraw(uint256 _amount) internal virtual;
function _approveToken(uint256 _amount) internal virtual;
/**
* @notice Withdraw collateral to payback excess debt in pool.
* @param _excessDebt Excess debt of strategy in collateral token
* @return _payback amount in collateral token. Usually it is equal to excess debt.
*/
function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback);
/**
* @notice Calculate earning and withdraw/convert it into collateral token.
* @param _totalDebt Total collateral debt of this strategy
* @return _profit Profit in collateral token
*/
function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit);
/**
* @notice Calculate loss
* @param _totalDebt Total collateral debt of this strategy
* @return _loss Realized loss in collateral token
*/
function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss);
/**
* @notice Reinvest collateral.
* @dev Once we file report back in pool, we might have some collateral in hand
* which we want to reinvest aka deposit in lender/provider.
*/
function _reinvest() internal virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./MakerStrategy.sol";
import "../../interfaces/compound/ICompound.sol";
/// @dev This strategy will deposit collateral token in Maker, borrow Dai and
/// deposit borrowed DAI in Compound to earn interest.
abstract contract CompoundMakerStrategy is MakerStrategy {
using SafeERC20 for IERC20;
address internal constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
CToken internal immutable cToken;
Comptroller internal constant COMPTROLLER = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
constructor(
address _pool,
address _cm,
address _swapManager,
address _receiptToken,
bytes32 _collateralType
) MakerStrategy(_pool, _cm, _swapManager, _receiptToken, _collateralType) {
require(_receiptToken != address(0), "cToken-address-is-zero");
cToken = CToken(_receiptToken);
}
/**
* @notice Report total value of this strategy
* @dev Make sure to return value in collateral token.
* @dev Total value = DAI earned + COMP earned + Collateral locked in Maker
*/
function totalValue() external view virtual override returns (uint256 _totalValue) {
uint256 _daiBalance = _getDaiBalance();
uint256 _debt = cm.getVaultDebt(address(this));
if (_daiBalance > _debt) {
uint256 _daiEarned = _daiBalance - _debt;
(, _totalValue) = swapManager.bestPathFixedInput(DAI, address(collateralToken), _daiEarned, 0);
}
uint256 _compAccrued = COMPTROLLER.compAccrued(address(this));
if (_compAccrued != 0) {
(, uint256 _compAsCollateral) =
swapManager.bestPathFixedInput(COMP, address(collateralToken), _compAccrued, 0);
_totalValue += _compAsCollateral;
}
_totalValue += convertFrom18(cm.getVaultBalance(address(this)));
}
/// @dev Check whether given token is reserved or not. Reserved tokens are not allowed to sweep.
function isReservedToken(address _token) public view override returns (bool) {
return _token == receiptToken || _token == COMP;
}
/**
* @notice Returns true if pool is underwater.
* @notice Underwater - If debt is greater than earning of pool.
* @notice Earning - Sum of DAI balance and DAI from accrued reward, if any, in lending pool.
* @dev There can be a scenario when someone calls claimComp() periodically which will
* leave compAccrued = 0 and pool might be underwater. Call rebalance() to liquidate COMP.
*/
function isUnderwater() public view override returns (bool) {
uint256 _compAccrued = COMPTROLLER.compAccrued(address(this));
uint256 _daiEarned;
if (_compAccrued != 0) {
(, _daiEarned) = swapManager.bestPathFixedInput(COMP, DAI, _compAccrued, 0);
}
return cm.getVaultDebt(address(this)) > (_getDaiBalance() + _daiEarned);
}
function _approveToken(uint256 _amount) internal override {
super._approveToken(_amount);
IERC20(DAI).safeApprove(address(receiptToken), _amount);
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
IERC20(COMP).safeApprove(address(swapManager.ROUTERS(i)), _amount);
}
}
/// @notice Claim rewardToken from lender and convert it into DAI
function _claimRewardsAndConvertTo(address _toToken) internal override {
address[] memory _markets = new address[](1);
_markets[0] = address(cToken);
COMPTROLLER.claimComp(address(this), _markets);
uint256 _compAmount = IERC20(COMP).balanceOf(address(this));
if (_compAmount > 0) {
_safeSwap(COMP, _toToken, _compAmount, 1);
}
}
function _depositDaiToLender(uint256 _amount) internal override {
if (_amount != 0) {
require(cToken.mint(_amount) == 0, "deposit-in-compound-failed");
}
}
function _getDaiBalance() internal view override returns (uint256) {
return (cToken.balanceOf(address(this)) * cToken.exchangeRateStored()) / 1e18;
}
/**
* @dev Rebalance DAI in lender. If lender has more DAI than DAI debt in Maker
* then withdraw excess DAI from lender. If lender is short on DAI, underwater,
* then deposit DAI to lender.
* @dev There may be a scenario where we do not have enough DAI to deposit to
* lender, in that case pool will be underwater even after rebalanceDai.
*/
function _rebalanceDaiInLender() internal override {
uint256 _daiDebtInMaker = cm.getVaultDebt(address(this));
uint256 _daiInLender = _getDaiBalance();
if (_daiInLender > _daiDebtInMaker) {
_withdrawDaiFromLender(_daiInLender - _daiDebtInMaker);
} else if (_daiInLender < _daiDebtInMaker) {
// We have more DAI debt in Maker than DAI in lender
uint256 _daiNeeded = _daiDebtInMaker - _daiInLender;
uint256 _daiBalanceHere = IERC20(DAI).balanceOf(address(this));
if (_daiBalanceHere > _daiNeeded) {
_depositDaiToLender(_daiNeeded);
} else {
_depositDaiToLender(_daiBalanceHere);
}
}
}
function _withdrawDaiFromLender(uint256 _amount) internal override {
require(cToken.redeemUnderlying(_amount) == 0, "withdraw-from-compound-failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./CompoundMakerStrategy.sol";
import "../../interfaces/token/IToken.sol";
//solhint-disable no-empty-blocks
contract CompoundMakerStrategyUNI is CompoundMakerStrategy {
string public constant NAME = "Compound-Maker-Strategy-UNI";
string public constant VERSION = "3.0.9";
// cDAI = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643
constructor(
address _pool,
address _cm,
address _swapManager
) CompoundMakerStrategy(_pool, _cm, _swapManager, 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643, "UNI-A") {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "../Strategy.sol";
import "../../interfaces/vesper/ICollateralManager.sol";
/// @dev This strategy will deposit collateral token in Maker, borrow Dai and
/// deposit borrowed DAI in other lending pool to earn interest.
abstract contract MakerStrategy is Strategy {
using SafeERC20 for IERC20;
address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
ICollateralManager public immutable cm;
bytes32 public immutable collateralType;
uint256 public highWater;
uint256 public lowWater;
uint256 private constant WAT = 10**16;
constructor(
address _pool,
address _cm,
address _swapManager,
address _receiptToken,
bytes32 _collateralType
) Strategy(_pool, _swapManager, _receiptToken) {
require(_cm != address(0), "cm-address-is-zero");
collateralType = _collateralType;
cm = ICollateralManager(_cm);
}
/// @notice Create new Maker vault
function createVault() external onlyGovernor {
cm.createVault(collateralType);
}
/**
* @dev If pool is underwater this function will resolve underwater condition.
* If Debt in Maker is greater than Dai balance in lender then pool is underwater.
* Lowering DAI debt in Maker will resolve underwater condition.
* Resolve: Calculate required collateral token to lower DAI debt. Withdraw required
* collateral token from Maker and convert those to DAI via Uniswap.
* Finally payback debt in Maker using DAI.
* @dev Also report loss in pool.
*/
function resurface() external onlyKeeper {
_resurface();
}
/**
* @notice Update balancing factors aka high water and low water values.
* Water mark values represent Collateral Ratio in Maker. For example 300 as high water
* means 300% collateral ratio.
* @param _highWater Value for high water mark.
* @param _lowWater Value for low water mark.
*/
function updateBalancingFactor(uint256 _highWater, uint256 _lowWater) external onlyGovernor {
require(_lowWater != 0, "lowWater-is-zero");
require(_highWater > _lowWater, "highWater-less-than-lowWater");
highWater = _highWater * WAT;
lowWater = _lowWater * WAT;
}
/**
* @notice Report total value of this strategy
* @dev Make sure to return value in collateral token and in order to do that
* we are using Uniswap to get collateral amount for earned DAI.
*/
function totalValue() external view virtual override returns (uint256 _totalValue) {
uint256 _daiBalance = _getDaiBalance();
uint256 _debt = cm.getVaultDebt(address(this));
if (_daiBalance > _debt) {
uint256 _daiEarned = _daiBalance - _debt;
(, _totalValue) = swapManager.bestPathFixedInput(DAI, address(collateralToken), _daiEarned, 0);
}
_totalValue += convertFrom18(cm.getVaultBalance(address(this)));
}
function vaultNum() external view returns (uint256) {
return cm.vaultNum(address(this));
}
/// @dev Check whether given token is reserved or not. Reserved tokens are not allowed to sweep.
function isReservedToken(address _token) public view virtual override returns (bool) {
return _token == receiptToken;
}
/**
* @notice Returns true if pool is underwater.
* @notice Underwater - If debt is greater than earning of pool.
* @notice Earning - Sum of DAI balance and DAI from accrued reward, if any, in lending pool.
*/
function isUnderwater() public view virtual returns (bool) {
return cm.getVaultDebt(address(this)) > _getDaiBalance();
}
/**
* @notice Before migration hook. It will be called during migration
* @dev Transfer Maker vault ownership to new strategy
* @param _newStrategy Address of new strategy.
*/
function _beforeMigration(address _newStrategy) internal virtual override {
cm.transferVaultOwnership(_newStrategy);
}
function _approveToken(uint256 _amount) internal virtual override {
IERC20(DAI).safeApprove(address(cm), _amount);
collateralToken.safeApprove(address(cm), _amount);
collateralToken.safeApprove(pool, _amount);
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
collateralToken.safeApprove(address(swapManager.ROUTERS(i)), _amount);
IERC20(DAI).safeApprove(address(swapManager.ROUTERS(i)), _amount);
}
}
function _moveDaiToMaker(uint256 _amount) internal {
if (_amount != 0) {
_withdrawDaiFromLender(_amount);
cm.payback(_amount);
}
}
function _moveDaiFromMaker(uint256 _amount) internal virtual {
cm.borrow(_amount);
_amount = IERC20(DAI).balanceOf(address(this));
_depositDaiToLender(_amount);
}
/**
* @notice Withdraw collateral to payback excess debt in pool.
* @param _excessDebt Excess debt of strategy in collateral token
* @return payback amount in collateral token. Usually it is equal to excess debt.
*/
function _liquidate(uint256 _excessDebt) internal virtual override returns (uint256) {
_withdrawHere(_excessDebt);
return _excessDebt;
}
/**
* @notice Calculate earning and convert it to collateral token
* @dev Also claim rewards if available.
* Withdraw excess DAI from lender.
* Swap net earned DAI to collateral token
* @return profit in collateral token
*/
function _realizeProfit(
uint256 /*_totalDebt*/
) internal virtual override returns (uint256) {
_claimRewardsAndConvertTo(DAI);
_rebalanceDaiInLender();
uint256 _daiBalance = IERC20(DAI).balanceOf(address(this));
if (_daiBalance != 0) {
_safeSwap(DAI, address(collateralToken), _daiBalance, 1);
}
return collateralToken.balanceOf(address(this));
}
/**
* @notice Calculate collateral loss from resurface, if any
* @dev Difference of total debt of strategy in pool and collateral locked
* in Maker vault is the loss.
* @return loss in collateral token
*/
function _realizeLoss(uint256 _totalDebt) internal virtual override returns (uint256) {
uint256 _collateralLocked = convertFrom18(cm.getVaultBalance(address(this)));
return _totalDebt > _collateralLocked ? _totalDebt - _collateralLocked : 0;
}
/**
* @notice Deposit collateral in Maker and rebalance collateral and debt in Maker.
* @dev Based on defined risk parameter either borrow more DAI from Maker or
* payback some DAI in Maker. It will try to mitigate risk of liquidation.
*/
function _reinvest() internal virtual override {
uint256 _collateralBalance = collateralToken.balanceOf(address(this));
if (_collateralBalance != 0) {
cm.depositCollateral(_collateralBalance);
}
(
uint256 _collateralLocked,
uint256 _currentDebt,
uint256 _collateralUsdRate,
uint256 _collateralRatio,
uint256 _minimumAllowedDebt
) = cm.getVaultInfo(address(this));
uint256 _maxDebt = (_collateralLocked * _collateralUsdRate) / highWater;
if (_maxDebt < _minimumAllowedDebt) {
// Dusting Scenario:: Based on collateral locked, if our max debt is less
// than Maker defined minimum debt then payback whole debt and wind up.
_moveDaiToMaker(_currentDebt);
} else {
if (_collateralRatio > highWater) {
require(!isUnderwater(), "pool-is-underwater");
// Safe to borrow more DAI
_moveDaiFromMaker(_maxDebt - _currentDebt);
} else if (_collateralRatio < lowWater) {
// Being below low water brings risk of liquidation in Maker.
// Withdraw DAI from Lender and deposit in Maker
_moveDaiToMaker(_currentDebt - _maxDebt);
}
}
}
function _resurface() internal virtual {
require(isUnderwater(), "pool-is-above-water");
uint256 _daiNeeded = cm.getVaultDebt(address(this)) - _getDaiBalance();
(address[] memory _path, uint256 _collateralNeeded, uint256 rIdx) =
swapManager.bestInputFixedOutput(address(collateralToken), DAI, _daiNeeded);
if (_collateralNeeded != 0) {
cm.withdrawCollateral(_collateralNeeded);
swapManager.ROUTERS(rIdx).swapExactTokensForTokens(
_collateralNeeded,
1,
_path,
address(this),
block.timestamp
);
cm.payback(IERC20(DAI).balanceOf(address(this)));
IVesperPool(pool).reportLoss(_daiNeeded);
}
}
function _withdraw(uint256 _amount) internal override {
_withdrawHere(_amount);
collateralToken.safeTransfer(pool, collateralToken.balanceOf(address(this)));
}
// TODO do we need a safe withdraw
function _withdrawHere(uint256 _amount) internal {
(
uint256 collateralLocked,
uint256 debt,
uint256 collateralUsdRate,
uint256 collateralRatio,
uint256 minimumDebt
) = cm.whatWouldWithdrawDo(address(this), _amount);
if (debt != 0 && collateralRatio < lowWater) {
// If this withdraw results in Low Water scenario.
uint256 maxDebt = (collateralLocked * collateralUsdRate) / highWater;
if (maxDebt < minimumDebt) {
// This is Dusting scenario
_moveDaiToMaker(debt);
} else if (maxDebt < debt) {
_moveDaiToMaker(debt - maxDebt);
}
}
cm.withdrawCollateral(_amount);
}
function _depositDaiToLender(uint256 _amount) internal virtual;
function _rebalanceDaiInLender() internal virtual;
function _withdrawDaiFromLender(uint256 _amount) internal virtual;
function _getDaiBalance() internal view virtual returns (uint256);
}
| These methods must be implemented by the inheriting strategy* @notice Withdraw collateral to payback excess debt in pool. @param _excessDebt Excess debt of strategy in collateral token @return _payback amount in collateral token. Usually it is equal to excess debt./* @notice Calculate earning and withdraw/convert it into collateral token. @param _totalDebt Total collateral debt of this strategy @return _profit Profit in collateral token/* @notice Calculate loss @param _totalDebt Total collateral debt of this strategy @return _loss Realized loss in collateral token/* @notice Reinvest collateral. @dev Once we file report back in pool, we might have some collateral in hand which we want to reinvest aka deposit in lender/provider./ SPDX-License-Identifier: MIT @dev This strategy will deposit collateral token in Maker, borrow Dai and deposit borrowed DAI in Compound to earn interest. | abstract contract CompoundMakerStrategy is MakerStrategy {
using SafeERC20 for IERC20;
address internal constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
CToken internal immutable cToken;
Comptroller internal constant COMPTROLLER = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
constructor(
address _pool,
address _cm,
address _swapManager,
address _receiptToken,
bytes32 _collateralType
function _withdraw(uint256 _amount) internal virtual;
function _approveToken(uint256 _amount) internal virtual;
function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback);
function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit);
function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss);
function _reinvest() internal virtual;
}
pragma solidity 0.8.3;
import "./MakerStrategy.sol";
import "../../interfaces/compound/ICompound.sol";
) MakerStrategy(_pool, _cm, _swapManager, _receiptToken, _collateralType) {
require(_receiptToken != address(0), "cToken-address-is-zero");
cToken = CToken(_receiptToken);
}
function totalValue() external view virtual override returns (uint256 _totalValue) {
uint256 _daiBalance = _getDaiBalance();
uint256 _debt = cm.getVaultDebt(address(this));
if (_daiBalance > _debt) {
uint256 _daiEarned = _daiBalance - _debt;
(, _totalValue) = swapManager.bestPathFixedInput(DAI, address(collateralToken), _daiEarned, 0);
}
uint256 _compAccrued = COMPTROLLER.compAccrued(address(this));
if (_compAccrued != 0) {
(, uint256 _compAsCollateral) =
swapManager.bestPathFixedInput(COMP, address(collateralToken), _compAccrued, 0);
_totalValue += _compAsCollateral;
}
_totalValue += convertFrom18(cm.getVaultBalance(address(this)));
}
function totalValue() external view virtual override returns (uint256 _totalValue) {
uint256 _daiBalance = _getDaiBalance();
uint256 _debt = cm.getVaultDebt(address(this));
if (_daiBalance > _debt) {
uint256 _daiEarned = _daiBalance - _debt;
(, _totalValue) = swapManager.bestPathFixedInput(DAI, address(collateralToken), _daiEarned, 0);
}
uint256 _compAccrued = COMPTROLLER.compAccrued(address(this));
if (_compAccrued != 0) {
(, uint256 _compAsCollateral) =
swapManager.bestPathFixedInput(COMP, address(collateralToken), _compAccrued, 0);
_totalValue += _compAsCollateral;
}
_totalValue += convertFrom18(cm.getVaultBalance(address(this)));
}
function totalValue() external view virtual override returns (uint256 _totalValue) {
uint256 _daiBalance = _getDaiBalance();
uint256 _debt = cm.getVaultDebt(address(this));
if (_daiBalance > _debt) {
uint256 _daiEarned = _daiBalance - _debt;
(, _totalValue) = swapManager.bestPathFixedInput(DAI, address(collateralToken), _daiEarned, 0);
}
uint256 _compAccrued = COMPTROLLER.compAccrued(address(this));
if (_compAccrued != 0) {
(, uint256 _compAsCollateral) =
swapManager.bestPathFixedInput(COMP, address(collateralToken), _compAccrued, 0);
_totalValue += _compAsCollateral;
}
_totalValue += convertFrom18(cm.getVaultBalance(address(this)));
}
function isReservedToken(address _token) public view override returns (bool) {
return _token == receiptToken || _token == COMP;
}
function isUnderwater() public view override returns (bool) {
uint256 _compAccrued = COMPTROLLER.compAccrued(address(this));
uint256 _daiEarned;
if (_compAccrued != 0) {
(, _daiEarned) = swapManager.bestPathFixedInput(COMP, DAI, _compAccrued, 0);
}
return cm.getVaultDebt(address(this)) > (_getDaiBalance() + _daiEarned);
}
function isUnderwater() public view override returns (bool) {
uint256 _compAccrued = COMPTROLLER.compAccrued(address(this));
uint256 _daiEarned;
if (_compAccrued != 0) {
(, _daiEarned) = swapManager.bestPathFixedInput(COMP, DAI, _compAccrued, 0);
}
return cm.getVaultDebt(address(this)) > (_getDaiBalance() + _daiEarned);
}
function _approveToken(uint256 _amount) internal override {
super._approveToken(_amount);
IERC20(DAI).safeApprove(address(receiptToken), _amount);
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
IERC20(COMP).safeApprove(address(swapManager.ROUTERS(i)), _amount);
}
}
function _approveToken(uint256 _amount) internal override {
super._approveToken(_amount);
IERC20(DAI).safeApprove(address(receiptToken), _amount);
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
IERC20(COMP).safeApprove(address(swapManager.ROUTERS(i)), _amount);
}
}
function _claimRewardsAndConvertTo(address _toToken) internal override {
address[] memory _markets = new address[](1);
_markets[0] = address(cToken);
COMPTROLLER.claimComp(address(this), _markets);
uint256 _compAmount = IERC20(COMP).balanceOf(address(this));
if (_compAmount > 0) {
_safeSwap(COMP, _toToken, _compAmount, 1);
}
}
function _claimRewardsAndConvertTo(address _toToken) internal override {
address[] memory _markets = new address[](1);
_markets[0] = address(cToken);
COMPTROLLER.claimComp(address(this), _markets);
uint256 _compAmount = IERC20(COMP).balanceOf(address(this));
if (_compAmount > 0) {
_safeSwap(COMP, _toToken, _compAmount, 1);
}
}
function _depositDaiToLender(uint256 _amount) internal override {
if (_amount != 0) {
require(cToken.mint(_amount) == 0, "deposit-in-compound-failed");
}
}
function _depositDaiToLender(uint256 _amount) internal override {
if (_amount != 0) {
require(cToken.mint(_amount) == 0, "deposit-in-compound-failed");
}
}
function _getDaiBalance() internal view override returns (uint256) {
return (cToken.balanceOf(address(this)) * cToken.exchangeRateStored()) / 1e18;
}
function _rebalanceDaiInLender() internal override {
uint256 _daiDebtInMaker = cm.getVaultDebt(address(this));
uint256 _daiInLender = _getDaiBalance();
if (_daiInLender > _daiDebtInMaker) {
_withdrawDaiFromLender(_daiInLender - _daiDebtInMaker);
uint256 _daiNeeded = _daiDebtInMaker - _daiInLender;
uint256 _daiBalanceHere = IERC20(DAI).balanceOf(address(this));
if (_daiBalanceHere > _daiNeeded) {
_depositDaiToLender(_daiNeeded);
_depositDaiToLender(_daiBalanceHere);
}
}
}
function _rebalanceDaiInLender() internal override {
uint256 _daiDebtInMaker = cm.getVaultDebt(address(this));
uint256 _daiInLender = _getDaiBalance();
if (_daiInLender > _daiDebtInMaker) {
_withdrawDaiFromLender(_daiInLender - _daiDebtInMaker);
uint256 _daiNeeded = _daiDebtInMaker - _daiInLender;
uint256 _daiBalanceHere = IERC20(DAI).balanceOf(address(this));
if (_daiBalanceHere > _daiNeeded) {
_depositDaiToLender(_daiNeeded);
_depositDaiToLender(_daiBalanceHere);
}
}
}
} else if (_daiInLender < _daiDebtInMaker) {
function _rebalanceDaiInLender() internal override {
uint256 _daiDebtInMaker = cm.getVaultDebt(address(this));
uint256 _daiInLender = _getDaiBalance();
if (_daiInLender > _daiDebtInMaker) {
_withdrawDaiFromLender(_daiInLender - _daiDebtInMaker);
uint256 _daiNeeded = _daiDebtInMaker - _daiInLender;
uint256 _daiBalanceHere = IERC20(DAI).balanceOf(address(this));
if (_daiBalanceHere > _daiNeeded) {
_depositDaiToLender(_daiNeeded);
_depositDaiToLender(_daiBalanceHere);
}
}
}
} else {
function _withdrawDaiFromLender(uint256 _amount) internal override {
require(cToken.redeemUnderlying(_amount) == 0, "withdraw-from-compound-failed");
}
}
| 11,996,521 | [
1,
29690,
2590,
1297,
506,
8249,
635,
326,
6811,
310,
6252,
225,
3423,
9446,
4508,
2045,
287,
358,
8843,
823,
23183,
18202,
88,
316,
2845,
18,
225,
389,
338,
614,
758,
23602,
1312,
614,
18202,
88,
434,
6252,
316,
4508,
2045,
287,
1147,
327,
389,
10239,
823,
3844,
316,
4508,
2045,
287,
1147,
18,
29785,
518,
353,
3959,
358,
23183,
18202,
88,
18,
19,
225,
9029,
425,
9542,
471,
598,
9446,
19,
6283,
518,
1368,
4508,
2045,
287,
1147,
18,
225,
389,
4963,
758,
23602,
10710,
4508,
2045,
287,
18202,
88,
434,
333,
6252,
327,
389,
685,
7216,
1186,
7216,
316,
4508,
2045,
287,
1147,
19,
225,
9029,
8324,
225,
389,
4963,
758,
23602,
10710,
4508,
2045,
287,
18202,
88,
434,
333,
6252,
327,
389,
7873,
15987,
1235,
8324,
316,
4508,
2045,
287,
1147,
19,
225,
868,
5768,
395,
4508,
2045,
287,
18,
225,
12419,
732,
585,
2605,
1473,
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,
17801,
6835,
21327,
12373,
4525,
353,
490,
6388,
4525,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
1758,
2713,
5381,
13846,
273,
374,
6511,
713,
73,
11290,
15237,
6028,
22,
39,
4763,
18212,
11149,
41,
26,
74,
10321,
28406,
3461,
26565,
37,
27,
74,
5558,
5482,
28,
31,
203,
565,
385,
1345,
2713,
11732,
276,
1345,
31,
203,
565,
1286,
337,
1539,
2713,
5381,
5423,
1856,
25353,
273,
1286,
337,
1539,
12,
20,
92,
23,
72,
10689,
15561,
2163,
37,
6938,
70,
7616,
9498,
70,
5082,
26897,
6564,
70,
41,
22,
8906,
40,
7235,
38,
29,
71,
29,
19728,
23,
38,
1769,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
6011,
16,
203,
3639,
1758,
389,
7670,
16,
203,
3639,
1758,
389,
22270,
1318,
16,
203,
3639,
1758,
389,
8606,
8138,
1345,
16,
203,
3639,
1731,
1578,
389,
12910,
2045,
287,
559,
203,
565,
445,
389,
1918,
9446,
12,
11890,
5034,
389,
8949,
13,
2713,
5024,
31,
203,
203,
565,
445,
389,
12908,
537,
1345,
12,
11890,
5034,
389,
8949,
13,
2713,
5024,
31,
203,
203,
565,
445,
389,
549,
26595,
340,
12,
11890,
5034,
389,
338,
614,
758,
23602,
13,
2713,
5024,
1135,
261,
11890,
5034,
389,
10239,
823,
1769,
203,
203,
565,
445,
389,
7688,
554,
626,
7216,
12,
11890,
5034,
389,
4963,
758,
23602,
13,
2713,
5024,
1135,
261,
11890,
5034,
389,
685,
7216,
1769,
203,
203,
565,
445,
389,
7688,
554,
20527,
12,
11890,
5034,
389,
4963,
758,
23602,
13,
2
] |
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File @openzeppelin/contracts/utils/[email protected]
// 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;
}
}
// File @openzeppelin/contracts/access/[email protected]
// MIT
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/token/ERC20/[email protected]
// 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);
}
// File contracts/MVM/iMVM_DiscountOracle.sol
// MIT
pragma solidity ^0.8.9;
interface iMVM_DiscountOracle{
function setDiscount(
uint256 _discount
) external;
function setMinL2Gas(
uint256 _minL2Gas
) external;
function setWhitelistedXDomainSender(
address _sender,
bool _isWhitelisted
) external;
function isXDomainSenderAllowed(
address _sender
) view external returns(bool);
function setAllowAllXDomainSenders(
bool _allowAllXDomainSenders
) external;
function getMinL2Gas() view external returns(uint256);
function getDiscount() view external returns(uint256);
function processL2SeqGas(address sender, uint256 _chainId) external payable;
}
// File contracts/libraries/resolver/Lib_AddressManager.sol
// MIT
pragma solidity ^0.8.9;
/* External Imports */
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(string indexed _name, address _newAddress, address _oldAddress);
/*************
* Variables *
*************/
mapping(bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(string memory _name, address _address) external onlyOwner {
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(_name, _address, oldAddress);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(string memory _name) external view returns (address) {
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(string memory _name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_name));
}
}
// File contracts/libraries/resolver/Lib_AddressResolver.sol
// MIT
pragma solidity ^0.8.9;
/* Library Imports */
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(address _libAddressManager) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(string memory _name) public view returns (address) {
return libAddressManager.getAddress(_name);
}
}
// File contracts/libraries/rlp/Lib_RLPReader.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 internal constant MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) {
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({ length: _in.length, ptr: ptr });
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) {
(uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value.");
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length.");
(uint256 itemOffset, uint256 itemLength, ) = _decodeLength(
RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })
);
out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset });
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(bytes memory _in) internal pure returns (RLPItem[] memory) {
return readList(toRLPItem(_in));
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(RLPItem memory _in) internal pure returns (bytes memory) {
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value.");
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(bytes memory _in) internal pure returns (bytes memory) {
return readBytes(toRLPItem(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(RLPItem memory _in) internal pure returns (string memory) {
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(bytes memory _in) internal pure returns (string memory) {
return readString(toRLPItem(_in));
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(RLPItem memory _in) internal pure returns (bytes32) {
require(_in.length <= 33, "Invalid RLP bytes32 value.");
(uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value.");
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(bytes memory _in) internal pure returns (bytes32) {
return readBytes32(toRLPItem(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(RLPItem memory _in) internal pure returns (uint256) {
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(bytes memory _in) internal pure returns (uint256) {
return readUint256(toRLPItem(_in));
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(RLPItem memory _in) internal pure returns (bool) {
require(_in.length == 1, "Invalid RLP boolean value.");
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1");
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(bytes memory _in) internal pure returns (bool) {
return readBool(toRLPItem(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(RLPItem memory _in) internal pure returns (address) {
if (_in.length == 1) {
return address(0);
}
require(_in.length == 21, "Invalid RLP address value.");
return address(uint160(readUint256(_in)));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(bytes memory _in) internal pure returns (address) {
return readAddress(toRLPItem(_in));
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) {
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(RLPItem memory _in)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(_in.length > 0, "RLP item cannot be null.");
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(_in.length > strLen, "Invalid RLP short string.");
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(_in.length > lenOfStrLen, "Invalid RLP long string length.");
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)))
}
require(_in.length > lenOfStrLen + strLen, "Invalid RLP long string.");
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(_in.length > listLen, "Invalid RLP short list.");
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(_in.length > lenOfListLen, "Invalid RLP long list length.");
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)))
}
require(_in.length > lenOfListLen + listLen, "Invalid RLP long list.");
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
) private pure returns (bytes memory) {
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask;
unchecked {
mask = 256**(32 - (_length % 32)) - 1;
}
assembly {
mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask)))
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(RLPItem memory _in) private pure returns (bytes memory) {
return _copy(_in.ptr, 0, _in.length);
}
}
// File contracts/libraries/rlp/Lib_RLPWriter.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(string memory _in) internal pure returns (bytes memory) {
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(address _in) internal pure returns (bytes memory) {
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(uint256 _in) internal pure returns (bytes memory) {
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(bool _in) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) {
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = bytes1(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256**(32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly {
flattenedPtr := add(flattened, 0x20)
}
for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// File contracts/libraries/utils/Lib_BytesUtils.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) {
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32(bytes memory _bytes) internal pure returns (bytes32) {
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(bytes memory _bytes) internal pure returns (uint256) {
return uint256(toBytes32(_bytes));
}
function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) {
return keccak256(_bytes) == keccak256(_other);
}
}
// File contracts/libraries/utils/Lib_Bytes32Utils.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(bytes32 _in) internal pure returns (bool) {
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(bool _in) internal pure returns (bytes32) {
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(bytes32 _in) internal pure returns (address) {
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(address _in) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_in)));
}
}
// File contracts/libraries/codec/Lib_OVMCodec.sol
// MIT
pragma solidity ^0.8.9;
/* Library Imports */
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(Transaction memory _transaction)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(Transaction memory _transaction) internal pure returns (bytes32) {
return keccak256(encodeTransaction(_transaction));
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(bytes memory _encoded) internal pure returns (EVMAccount memory) {
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return
EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// File contracts/libraries/utils/Lib_MerkleTree.sol
// MIT
pragma solidity ^0.8.9;
/**
* @title Lib_MerkleTree
* @author River Keefer
*/
library Lib_MerkleTree {
/**********************
* Internal Functions *
**********************/
/**
* Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number
* of leaves passed in is not a power of two, it pads out the tree with zero hashes.
* If you do not know the original length of elements for the tree you are verifying, then
* this may allow empty leaves past _elements.length to pass a verification check down the line.
* Note that the _elements argument is modified, therefore it must not be used again afterwards
* @param _elements Array of hashes from which to generate a merkle root.
* @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above).
*/
function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) {
require(_elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash.");
if (_elements.length == 1) {
return _elements[0];
}
uint256[16] memory defaults = [
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563,
0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d,
0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d,
0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8,
0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da,
0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5,
0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7,
0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead,
0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10,
0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82,
0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516,
0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c,
0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e,
0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab,
0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862,
0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10
];
// Reserve memory space for our hashes.
bytes memory buf = new bytes(64);
// We'll need to keep track of left and right siblings.
bytes32 leftSibling;
bytes32 rightSibling;
// Number of non-empty nodes at the current depth.
uint256 rowSize = _elements.length;
// Current depth, counting from 0 at the leaves
uint256 depth = 0;
// Common sub-expressions
uint256 halfRowSize; // rowSize / 2
bool rowSizeIsOdd; // rowSize % 2 == 1
while (rowSize > 1) {
halfRowSize = rowSize / 2;
rowSizeIsOdd = rowSize % 2 == 1;
for (uint256 i = 0; i < halfRowSize; i++) {
leftSibling = _elements[(2 * i)];
rightSibling = _elements[(2 * i) + 1];
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[i] = keccak256(buf);
}
if (rowSizeIsOdd) {
leftSibling = _elements[rowSize - 1];
rightSibling = bytes32(defaults[depth]);
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[halfRowSize] = keccak256(buf);
}
rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0);
depth++;
}
return _elements[0];
}
/**
* Verifies a merkle branch for the given leaf hash. Assumes the original length
* of leaves generated is a known, correct input, and does not return true for indices
* extending past that index (even if _siblings would be otherwise valid.)
* @param _root The Merkle root to verify against.
* @param _leaf The leaf hash to verify inclusion of.
* @param _index The index in the tree of this leaf.
* @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0
* (bottom of the tree).
* @param _totalLeaves The total number of leaves originally passed into.
* @return Whether or not the merkle branch and leaf passes verification.
*/
function verify(
bytes32 _root,
bytes32 _leaf,
uint256 _index,
bytes32[] memory _siblings,
uint256 _totalLeaves
) internal pure returns (bool) {
require(_totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero.");
require(_index < _totalLeaves, "Lib_MerkleTree: Index out of bounds.");
require(
_siblings.length == _ceilLog2(_totalLeaves),
"Lib_MerkleTree: Total siblings does not correctly correspond to total leaves."
);
bytes32 computedRoot = _leaf;
for (uint256 i = 0; i < _siblings.length; i++) {
if ((_index & 1) == 1) {
computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot));
} else {
computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i]));
}
_index >>= 1;
}
return _root == computedRoot;
}
/*********************
* Private Functions *
*********************/
/**
* Calculates the integer ceiling of the log base 2 of an input.
* @param _in Unsigned input to calculate the log.
* @return ceil(log_base_2(_in))
*/
function _ceilLog2(uint256 _in) private pure returns (uint256) {
require(_in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0.");
if (_in == 1) {
return 0;
}
// Find the highest set bit (will be floor(log_2)).
// Borrowed with <3 from https://github.com/ethereum/solidity-examples
uint256 val = _in;
uint256 highest = 0;
for (uint256 i = 128; i >= 1; i >>= 1) {
if (val & (((uint256(1) << i) - 1) << i) != 0) {
highest += i;
val >>= i;
}
}
// Increment by one if this is not a perfect logarithm.
if ((uint256(1) << highest) != _in) {
highest += 1;
}
return highest;
}
}
// File contracts/L1/rollup/IChainStorageContainer.sol
// MIT
pragma solidity >0.5.0 <0.9.0;
/**
* @title IChainStorageContainer
*/
interface IChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(bytes27 _globalMetadata) external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata() external view returns (bytes27);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length() external view returns (uint256);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(bytes32 _object) external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(bytes32 _object, bytes27 _globalMetadata) external;
/**
* Set an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _index position.
* @param _object A 32 byte value to insert into the container.
*/
function setByChainId(
uint256 _chainId,
uint256 _index,
bytes32 _object
)
external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(uint256 _index) external view returns (bytes32);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(uint256 _index) external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata) external;
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _chainId identity for the l2 chain.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadataByChainId(
uint256 _chainId,
bytes27 _globalMetadata
)
external;
/**
* Retrieves the container's global metadata field.
* @param _chainId identity for the l2 chain.
* @return Container global metadata field.
*/
function getGlobalMetadataByChainId(
uint256 _chainId
)
external
view
returns (
bytes27
);
/**
* Retrieves the number of objects stored in the container.
* @param _chainId identity for the l2 chain.
* @return Number of objects in the container.
*/
function lengthByChainId(
uint256 _chainId
)
external
view
returns (
uint256
);
/**
* Pushes an object into the container.
* @param _chainId identity for the l2 chain.
* @param _object A 32 byte value to insert into the container.
*/
function pushByChainId(
uint256 _chainId,
bytes32 _object
)
external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _chainId identity for the l2 chain.
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function pushByChainId(
uint256 _chainId,
bytes32 _object,
bytes27 _globalMetadata
)
external;
/**
* Retrieves an object from the container.
* @param _chainId identity for the l2 chain.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function getByChainId(
uint256 _chainId,
uint256 _index
)
external
view
returns (
bytes32
);
/**
* Removes all objects after and including a given index.
* @param _chainId identity for the l2 chain.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index
)
external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _chainId identity for the l2 chain.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusiveByChainId(
uint256 _chainId,
uint256 _index,
bytes27 _globalMetadata
)
external;
}
// File contracts/L1/rollup/IStateCommitmentChain.sol
// MIT
pragma solidity >0.5.0 <0.9.0;
/* Library Imports */
/**
* @title IStateCommitmentChain
*/
interface IStateCommitmentChain {
/**********
* Events *
**********/
event StateBatchAppended(
uint256 _chainId,
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
event StateBatchDeleted(
uint256 _chainId,
uint256 indexed _batchIndex,
bytes32 _batchRoot
);
/********************
* Public Functions *
********************/
function batches() external view returns (IChainStorageContainer);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() external view returns (uint256 _totalElements);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() external view returns (uint256 _totalBatches);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp);
/**
* Appends a batch of state roots to the chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatch(bytes32[] calldata _batch, uint256 _shouldStartAtElement) external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external;
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitment(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
) external view returns (bool _verified);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
external
view
returns (
bool _inside
);
/********************
* chain id added func *
********************/
/**
* Retrieves the total number of elements submitted.
* @param _chainId identity for the l2 chain.
* @return _totalElements Total submitted elements.
*/
function getTotalElementsByChainId(uint256 _chainId)
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @param _chainId identity for the l2 chain.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatchesByChainId(uint256 _chainId)
external
view
returns (
uint256 _totalBatches
);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @param _chainId identity for the l2 chain.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestampByChainId(uint256 _chainId)
external
view
returns (
uint256 _lastSequencerTimestamp
);
/**
* Appends a batch of state roots to the chain.
* @param _chainId identity for the l2 chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatchByChainId(
uint256 _chainId,
bytes32[] calldata _batch,
uint256 _shouldStartAtElement,
string calldata proposer
)
external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _chainId identity for the l2 chain.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatchByChainId(
uint256 _chainId,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external;
/**
* Verifies a batch inclusion proof.
* @param _chainId identity for the l2 chain.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitmentByChainId(
uint256 _chainId,
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
external
view
returns (
bool _verified
);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _chainId identity for the l2 chain.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindowByChainId(
uint256 _chainId,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external
view
returns (
bool _inside
);
}
// File contracts/MVM/MVM_Verifier.sol
// MIT
pragma solidity ^0.8.9;
/* Contract Imports */
/* External Imports */
contract MVM_Verifier is Lib_AddressResolver{
// second slot
address public metis;
enum SETTLEMENT {NOT_ENOUGH_VERIFIER, SAME_ROOT, AGREE, DISAGREE, PASS}
event NewChallenge(uint256 cIndex, uint256 chainID, Lib_OVMCodec.ChainBatchHeader header, uint256 timestamp);
event Verify1(uint256 cIndex, address verifier);
event Verify2(uint256 cIndex, address verifier);
event Finalize(uint256 cIndex, address sender, SETTLEMENT result);
event Penalize(address sender, uint256 stakeLost);
event Reward(address target, uint256 amount);
event Claim(address sender, uint256 amount);
event Withdraw(address sender, uint256 amount);
event Stake(address verifier, uint256 amount);
event SlashSequencer(uint256 chainID, address seq);
/*************
* Constants *
*************/
string constant public CONFIG_OWNER_KEY = "METIS_MANAGER";
//challenge info
struct Challenge {
address challenger;
uint256 chainID;
uint256 index;
Lib_OVMCodec.ChainBatchHeader header;
uint256 timestamp;
uint256 numQualifiedVerifiers;
uint256 numVerifiers;
address[] verifiers;
bool done;
}
mapping (address => uint256) public verifier_stakes;
mapping (uint256 => mapping (address=>bytes)) private challenge_keys;
mapping (uint256 => mapping (address=>bytes)) private challenge_key_hashes;
mapping (uint256 => mapping (address=>bytes)) private challenge_hashes;
mapping (address => uint256) public rewards;
mapping (address => uint8) public absence_strikes;
mapping (address => uint8) public consensus_strikes;
// only one active challenge for each chain chainid=>cIndex
mapping (uint256 => uint256) public chain_under_challenge;
// white list
mapping (address => bool) public whitelist;
bool useWhiteList;
address[] public verifiers;
Challenge[] public challenges;
uint public verifyWindow = 3600 * 24; // 24 hours of window to complete the each verify phase
uint public activeChallenges;
uint256 public minStake;
uint256 public seqStake;
uint256 public numQualifiedVerifiers;
uint FAIL_THRESHOLD = 2; // 1 time grace
uint ABSENCE_THRESHOLD = 4; // 2 times grace
modifier onlyManager {
require(
msg.sender == resolve(CONFIG_OWNER_KEY),
"MVM_Verifier: Function can only be called by the METIS_MANAGER."
);
_;
}
modifier onlyWhitelisted {
require(isWhiteListed(msg.sender), "only whitelisted verifiers can call");
_;
}
modifier onlyStaked {
require(isSufficientlyStaked(msg.sender), "insufficient stake");
_;
}
constructor(
)
Lib_AddressResolver(address(0))
{
}
// add stake as a verifier
function verifierStake(uint256 stake) public onlyWhitelisted{
require(activeChallenges == 0, "stake is currently prohibited"); //ongoing challenge
require(stake > 0, "zero stake not allowed");
require(IERC20(metis).transferFrom(msg.sender, address(this), stake), "transfer metis failed");
uint256 previousBalance = verifier_stakes[msg.sender];
verifier_stakes[msg.sender] += stake;
require(isSufficientlyStaked(msg.sender), "insufficient stake to qualify as a verifier");
if (previousBalance == 0) {
numQualifiedVerifiers++;
verifiers.push(msg.sender);
}
emit Stake(msg.sender, stake);
}
// start a new challenge
// @param chainID chainid
// @param header chainbatch header
// @param proposedHash encrypted hash of the correct state
// @param keyhash hash of the decryption key
//
// @dev why do we ask for key and keyhash? because we want verifiers compute the state instead
// of just copying from other verifiers.
function newChallenge(uint256 chainID, Lib_OVMCodec.ChainBatchHeader calldata header, bytes calldata proposedHash, bytes calldata keyhash)
public onlyWhitelisted onlyStaked {
uint tempIndex = chain_under_challenge[chainID] - 1;
require(tempIndex == 0 || block.timestamp - challenges[tempIndex].timestamp > verifyWindow * 2, "there is an ongoing challenge");
if (tempIndex > 0) {
finalize(tempIndex);
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
// while the root is encrypted, the timestamp is available in the extradata field of the header
require(stateChain.insideFraudProofWindow(header), "the batch is outside of the fraud proof window");
Challenge memory c;
c.chainID = chainID;
c.challenger = msg.sender;
c.timestamp = block.timestamp;
c.header = header;
challenges.push(c);
uint cIndex = challenges.length - 1;
// house keeping
challenge_hashes[cIndex][msg.sender] = proposedHash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++; // the challenger
// this will prevent stake change
activeChallenges++;
chain_under_challenge[chainID] = cIndex + 1; // +1 because 0 means no in-progress challenge
emit NewChallenge(cIndex, chainID, header, block.timestamp);
}
// phase 1 of the verify, provide an encrypted hash and the hash of the decryption key
// @param cIndex index of the challenge
// @param hash encrypted hash of the correct state (for the index referred in the challenge)
// @param keyhash hash of the decryption key
function verify1(uint256 cIndex, bytes calldata hash, bytes calldata keyhash) public onlyWhitelisted onlyStaked{
require(challenge_hashes[cIndex][msg.sender].length == 0, "verify1 already completed for the sender");
challenge_hashes[cIndex][msg.sender] = hash;
challenge_key_hashes[cIndex][msg.sender] = keyhash;
challenges[cIndex].numVerifiers++;
emit Verify1(cIndex, msg.sender);
}
// phase 2 of the verify, provide the actual key to decrypt the hash
// @param cIndex index of the challenge
// @param key the decryption key
function verify2(uint256 cIndex, bytes calldata key) public onlyStaked onlyWhitelisted{
require(challenges[cIndex].numVerifiers == numQualifiedVerifiers
|| block.timestamp - challenges[cIndex].timestamp > verifyWindow, "phase 2 not ready");
require(challenge_hashes[cIndex][msg.sender].length > 0, "you didn't participate in phase 1");
if (challenge_keys[cIndex][msg.sender].length > 0) {
finalize(cIndex);
return;
}
//verify whether the key matches the keyhash initially provided.
require(sha256(key) == bytes32(challenge_key_hashes[cIndex][msg.sender]), "key and keyhash don't match");
if (msg.sender == challenges[cIndex].challenger) {
//decode the root in the header too
challenges[cIndex].header.batchRoot = bytes32(decrypt(abi.encodePacked(challenges[cIndex].header.batchRoot), key));
}
challenge_keys[cIndex][msg.sender] = key;
challenge_hashes[cIndex][msg.sender] = decrypt(challenge_hashes[cIndex][msg.sender], key);
challenges[cIndex].verifiers.push(msg.sender);
emit Verify2(cIndex, msg.sender);
finalize(cIndex);
}
function finalize(uint256 cIndex) internal {
Challenge storage challenge = challenges[cIndex];
require(challenge.done == false, "challenge is closed");
if (challenge.verifiers.length != challenge.numVerifiers
&& block.timestamp - challenge.timestamp < verifyWindow * 2) {
// not ready to finalize. do nothing
return;
}
IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain"));
bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]);
uint reward = 0;
address[] memory agrees = new address[](challenge.verifiers.length);
uint numAgrees = 0;
address[] memory disagrees = new address[](challenge.verifiers.length);
uint numDisagrees = 0;
for (uint256 i = 0; i < verifiers.length; i++) {
if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) {
// not qualified as a verifier
continue;
}
//record the agreement
if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) {
//agree with the challenger
if (absence_strikes[verifiers[i]] > 0) {
absence_strikes[verifiers[i]] -= 1; // slowly clear the strike
}
agrees[numAgrees] = verifiers[i];
numAgrees++;
} else if (challenge_keys[cIndex][verifiers[i]].length == 0) {
//absent
absence_strikes[verifiers[i]] += 2;
if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) {
reward += penalize(verifiers[i]);
}
} else {
//disagree with the challenger
if (absence_strikes[verifiers[i]] > 0) {
absence_strikes[verifiers[i]] -= 1; // slowly clear the strike
}
disagrees[numDisagrees] = verifiers[i];
numDisagrees++;
}
}
if (Lib_OVMCodec.hashBatchHeader(challenge.header) !=
stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) {
// wrong header, penalize the challenger
reward += penalize(challenge.challenger);
// reward the disagrees. but no penalty on agrees because the input
// is garbage.
distributeReward(reward, disagrees, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
} else if (challenge.verifiers.length < numQualifiedVerifiers * 75 / 100) {
// the absent verifiers get a absense strike. no other penalties. already done
emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER);
}
else if (proposedHash != challenge.header.batchRoot) {
if (numAgrees <= numDisagrees) {
// no consensus, challenge failed.
for (uint i = 0; i < numAgrees; i++) {
consensus_strikes[agrees[i]] += 2;
if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) {
reward += penalize(agrees[i]);
}
}
distributeReward(reward, disagrees, disagrees.length);
emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE);
} else {
// reached agreement. delete the batch root and slash the sequencer if the header is still valid
if(stateChain.insideFraudProofWindow(challenge.header)) {
// this header needs to be within the window
stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header);
// temporary for the p1 of the decentralization roadmap
if (seqStake > 0) {
reward += seqStake;
for (uint i = 0; i < numDisagrees; i++) {
consensus_strikes[disagrees[i]] += 2;
if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) {
reward += penalize(disagrees[i]);
}
}
distributeReward(reward, agrees, agrees.length);
}
emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE);
} else {
//not in the window anymore. let it pass... no penalty
emit Finalize(cIndex, msg.sender, SETTLEMENT.PASS);
}
}
} else {
//wasteful challenge, add consensus_strikes to the challenger
consensus_strikes[challenge.challenger] += 2;
if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) {
reward += penalize(challenge.challenger);
}
distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1);
emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT);
}
challenge.done = true;
activeChallenges--;
chain_under_challenge[challenge.chainID] = 0;
}
function depositSeqStake(uint256 amount) public onlyManager {
require(IERC20(metis).transferFrom(msg.sender, address(this), amount), "transfer metis failed");
seqStake += amount;
emit Stake(msg.sender, amount);
}
function withdrawSeqStake(address to) public onlyManager {
require(seqStake > 0, "no stake");
emit Withdraw(msg.sender, seqStake);
uint256 amount = seqStake;
seqStake = 0;
require(IERC20(metis).transfer(to, amount), "transfer metis failed");
}
function claim() public {
require(rewards[msg.sender] > 0, "no reward to claim");
uint256 amount = rewards[msg.sender];
rewards[msg.sender] = 0;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
emit Claim(msg.sender, amount);
}
function withdraw(uint256 amount) public {
require(activeChallenges == 0, "withdraw is currently prohibited"); //ongoing challenge
uint256 balance = verifier_stakes[msg.sender];
require(balance >= amount, "insufficient stake to withdraw");
if (balance - amount < minStake && balance >= minStake) {
numQualifiedVerifiers--;
deleteVerifier(msg.sender);
}
verifier_stakes[msg.sender] -= amount;
require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed");
}
function setMinStake(
uint256 _minStake
)
public
onlyManager
{
minStake = _minStake;
uint num = 0;
if (verifiers.length > 0) {
address[] memory arr = new address[](verifiers.length);
for (uint i = 0; i < verifiers.length; ++i) {
if (verifier_stakes[verifiers[i]] >= minStake) {
arr[num] = verifiers[i];
num++;
}
}
if (num < verifiers.length) {
delete verifiers;
for (uint i = 0; i < num; i++) {
verifiers.push(arr[i]);
}
}
}
numQualifiedVerifiers = num;
}
// helper
function isWhiteListed(address verifier) view public returns(bool){
return !useWhiteList || whitelist[verifier];
}
function isSufficientlyStaked (address target) view public returns(bool) {
return (verifier_stakes[target] >= minStake);
}
// set the length of the time windows for each verification phase
function setVerifyWindow (uint256 window) onlyManager public {
verifyWindow = window;
}
// add the verifier to the whitelist
function setWhiteList(address verifier, bool allowed) public onlyManager {
whitelist[verifier] = allowed;
useWhiteList = true;
}
// allow everyone to be the verifier
function disableWhiteList() public onlyManager {
useWhiteList = false;
}
function setThreshold(uint absence_threshold, uint fail_threshold) public onlyManager {
ABSENCE_THRESHOLD = absence_threshold;
FAIL_THRESHOLD = fail_threshold;
}
function getMerkleRoot(bytes32[] calldata elements) pure public returns (bytes32) {
return Lib_MerkleTree.getMerkleRoot(elements);
}
//helper fucntion to encrypt data
function encrypt(bytes calldata data, bytes calldata key) pure public returns (bytes memory) {
bytes memory encryptedData = data;
uint j = 0;
for (uint i = 0; i < encryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
encryptedData[i] = encryptByte(encryptedData[i], uint8(key[j]));
j++;
}
return encryptedData;
}
function encryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
temp16 += k;
if (temp16 > 255) {
temp16 -= 256;
}
return bytes1(uint8(temp16));
}
// helper fucntion to decrypt the data
function decrypt(bytes memory data, bytes memory key) pure public returns (bytes memory) {
bytes memory decryptedData = data;
uint j = 0;
for (uint i = 0; i < decryptedData.length; i++) {
if (j == key.length) {
j = 0;
}
decryptedData[i] = decryptByte(decryptedData[i], uint8(key[j]));
j++;
}
return decryptedData;
}
function decryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) {
uint16 temp16 = uint16(uint8(b));
if (temp16 > k) {
temp16 -= k;
} else {
temp16 = 256 - k;
}
return bytes1(uint8(temp16));
}
// calculate the rewards
function distributeReward(uint256 amount, address[] memory list, uint num) internal {
uint reward = amount / num;
if (reward == 0) {
return;
}
uint total = 0;
for (uint i; i < list.length; i++) {
if (isSufficientlyStaked(list[i])) {
rewards[list[i]] += reward;
total += reward;
emit Reward(list[i], reward);
}
}
if (total < amount) {
if (isSufficientlyStaked(list[0])) {
rewards[list[0]] += total - amount;
emit Reward(list[0], total - amount);
} else {
rewards[list[1]] += total - amount;
emit Reward(list[1], total - amount);
}
}
}
// slash the verifier stake
function penalize(address target) internal returns(uint256) {
uint256 stake = verifier_stakes[target];
verifier_stakes[target] = 0;
numQualifiedVerifiers--;
deleteVerifier(target);
emit Penalize(target, stake);
return stake;
}
function deleteVerifier(address target) internal {
bool hasVerifier = false;
uint pos = 0;
for (uint i = 0; i < verifiers.length; i++){
if (verifiers[i] == target) {
hasVerifier = true;
pos = i;
break;
}
}
if (hasVerifier) {
for (uint i = pos; i < verifiers.length-1; i++) {
verifiers[i] = verifiers[i+1];
}
verifiers.pop();
}
}
} | * Reads an RLP address value into a address. @param _in RLP address value. @return Decoded address./ | function readAddress(RLPItem memory _in) internal pure returns (address) {
if (_in.length == 1) {
return address(0);
}
require(_in.length == 21, "Invalid RLP address value.");
return address(uint160(readUint256(_in)));
}
| 366,087 | [
1,
7483,
392,
534,
14461,
1758,
460,
1368,
279,
1758,
18,
225,
389,
267,
534,
14461,
1758,
460,
18,
327,
6209,
72,
1758,
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
] | [
1,
1,
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,
855,
1887,
12,
54,
48,
1102,
874,
3778,
389,
267,
13,
2713,
16618,
1135,
261,
2867,
13,
288,
203,
3639,
309,
261,
67,
267,
18,
2469,
422,
404,
13,
288,
203,
5411,
327,
1758,
12,
20,
1769,
203,
3639,
289,
203,
203,
3639,
2583,
24899,
267,
18,
2469,
422,
9035,
16,
315,
1941,
534,
14461,
1758,
460,
1199,
1769,
203,
203,
3639,
327,
1758,
12,
11890,
16874,
12,
896,
5487,
5034,
24899,
267,
3719,
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
] |
./full_match/1/0xd068C7C941FbbD2300cB2f1841858c2643722DC7/sources/contracts/BaseERC20Token.sol | * @dev Moves `amount` of tokens from `from` to `to`. 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: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing. | function _transfer(
address from,
address to,
uint256 amount
) internal {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
_balances[to] += amount;
}
emit Transfer(from, to, amount);
}
| 4,934,691 | [
1,
19297,
1375,
8949,
68,
434,
2430,
628,
1375,
2080,
68,
358,
1375,
869,
8338,
1220,
2713,
445,
353,
7680,
358,
288,
13866,
5779,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
2348,
5859,
1147,
1656,
281,
16,
9026,
310,
1791,
28757,
16,
5527,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
29076,
30,
300,
1375,
2080,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
869,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
2080,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
19,
10752,
2426,
486,
3323,
30,
326,
2142,
434,
777,
324,
26488,
353,
3523,
1845,
635,
2078,
3088,
1283,
16,
471,
326,
2142,
353,
21096,
635,
15267,
310,
1508,
5504,
310,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
2254,
5034,
628,
13937,
273,
389,
70,
26488,
63,
2080,
15533,
203,
3639,
2583,
12,
2080,
13937,
1545,
3844,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
8863,
203,
565,
22893,
288,
203,
3639,
389,
70,
26488,
63,
2080,
65,
273,
628,
13937,
300,
3844,
31,
203,
3639,
389,
70,
26488,
63,
869,
65,
1011,
3844,
31,
203,
565,
289,
203,
203,
3639,
3626,
12279,
12,
2080,
16,
358,
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
] |
pragma solidity 0.6.12;
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
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);
}
}
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;
}
}
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);
}
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");
}
}
}
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
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 in 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");
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);
}
}
}
}
interface HermezVesting {
function move(address recipient, uint256 amount) external;
function changeAddress(address newAddress) external;
}
interface HEZ {
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
}
contract BootstrapDistribution {
using SafeMath for uint256;
HEZ public constant TOKEN_ADDRESS = HEZ(0xEEF9f339514298C6A857EfCfC1A762aF84438dEE);
HermezVesting public constant VESTING_0 = HermezVesting(0x8109dfB06D4d9e694a8349B855cBF493A0B22186);
HermezVesting public constant VESTING_1 = HermezVesting(0xDd90cA911a5dbfB1624fF7Eb586901a9b4BFC53D);
HermezVesting public constant VESTING_2 = HermezVesting(0xB213aeAeF76f82e42263fe896433A260EF018df2);
HermezVesting public constant VESTING_3 = HermezVesting(0x3049399e1308db7d2b28488880C6cFE9Aa003275);
address public constant MULTISIG_VESTING_2 = 0xC21BE548060cB6E07017bFc0b926A71b5E638e09;
address public constant MULTISIG_VESTING_3 = 0x5Fa543E23a1B62e45d010f81AFC0602456BD1F1d;
address public constant VESTING_0_ADDRESS_0 = 0x94E886bB17451A7B82E594db12570a5AdFC2D453;
address public constant VESTING_0_ADDRESS_1 = 0x4FE10B3e306aC1F4b966Db07f031ae5780BC48fB;
address public constant VESTING_0_ADDRESS_2 = 0x6629300128CCdda1e88641Ba2941a22Ce82F5df9;
address public constant VESTING_0_ADDRESS_3 = 0xEb60e28Ce3aCa617d1E0293791c1903cF022b9Cd;
address public constant VESTING_0_ADDRESS_4 = 0x9a415E0cE643abc4AD953B651b2D7e4db2FF3bEa;
address public constant VESTING_0_ADDRESS_5 = 0x15b54c53093aF3e11d787db86e268a6C4F2F72A2;
address public constant VESTING_0_ADDRESS_6 = 0x3279c71F132833190F6cd1D6a9975FFBf8d7C6dC;
address public constant VESTING_0_ADDRESS_7 = 0x312e6f33155177774CDa1A3C4e9f077D93266063;
address public constant VESTING_0_ADDRESS_8 = 0x47690A724Ed551fe2ff1A5eBa335B7c1B7a40990;
address public constant VESTING_1_ADDRESS_0 = 0x80FbB6dd386FC98D2B387F37845A373c8441c069;
address public constant VESTING_2_ADDRESS_0 = 0xBd48F607E26d94772FB21ED1d814F9F116dBD95C;
address public constant VESTING_3_ADDRESS_0 = 0x520Cf70a2D0B3dfB7386A2Bc9F800321F62a5c3a;
address public constant NO_VESTED_ADDRESS_0 = 0x4D4a7675CC0eb0a3B1d81CbDcd828c4BD0D74155;
address public constant NO_VESTED_ADDRESS_1 = 0x9CdaeBd2bcEED9EB05a3B3cccd601A40CB0026be;
address public constant NO_VESTED_ADDRESS_2 = 0x9315F815002d472A3E993ac9dc7461f2601A3c09;
address public constant NO_VESTED_ADDRESS_3 = 0xF96A39d61F6972d8dC0CCd2A3c082eD922E096a7;
address public constant NO_VESTED_ADDRESS_4 = 0xA93Bb239509D16827B7ee9DA7dA6Fc8478837247;
address public constant NO_VESTED_ADDRESS_5 = 0x99Ae889E171B82BB04FD22E254024716932e5F2f;
uint256 public constant VESTING_0_AMOUNT = 20_000_000 ether;
uint256 public constant VESTING_1_AMOUNT = 10_000_000 ether;
uint256 public constant VESTING_2_AMOUNT = 6_200_000 ether;
uint256 public constant VESTING_3_AMOUNT = 17_500_000 ether;
uint256 public constant VESTING_0_ADDRESS_0_AMOUNT = 12_000_000 ether;
uint256 public constant VESTING_0_ADDRESS_1_AMOUNT = 1_850_000 ether;
uint256 public constant VESTING_0_ADDRESS_2_AMOUNT = 1_675_000 ether;
uint256 public constant VESTING_0_ADDRESS_3_AMOUNT = 1_300_000 ether;
uint256 public constant VESTING_0_ADDRESS_4_AMOUNT = 1_000_000 ether;
uint256 public constant VESTING_0_ADDRESS_5_AMOUNT = 750_000 ether;
uint256 public constant VESTING_0_ADDRESS_6_AMOUNT = 625_000 ether;
uint256 public constant VESTING_0_ADDRESS_7_AMOUNT = 525_000 ether;
uint256 public constant VESTING_0_ADDRESS_8_AMOUNT = 275_000 ether;
uint256 public constant VESTING_1_ADDRESS_0_AMOUNT = 10_000_000 ether;
uint256 public constant VESTING_2_ADDRESS_0_AMOUNT = 500_000 ether;
uint256 public constant VESTING_3_ADDRESS_0_AMOUNT = 300_000 ether;
uint256 public constant NO_VESTED_ADDRESS_0_AMOUNT = 19_000_000 ether;
uint256 public constant NO_VESTED_ADDRESS_1_AMOUNT = 9_000_000 ether;
uint256 public constant NO_VESTED_ADDRESS_2_AMOUNT = 7_500_000 ether;
uint256 public constant NO_VESTED_ADDRESS_3_AMOUNT = 5_000_000 ether;
uint256 public constant NO_VESTED_ADDRESS_4_AMOUNT = 3_000_000 ether;
uint256 public constant NO_VESTED_ADDRESS_5_AMOUNT = 2_800_000 ether;
uint256 public constant INTERMEDIATE_BALANCE = 46_300_000 ether;
function distribute() public {
require(
TOKEN_ADDRESS.balanceOf(address(this)) == (100_000_000 ether),
"BootstrapDistribution::distribute NOT_ENOUGH_BALANCE"
);
// Vested Tokens
// Transfer HEZ tokens
TOKEN_ADDRESS.transfer(address(VESTING_0),VESTING_0_AMOUNT);
TOKEN_ADDRESS.transfer(address(VESTING_1),VESTING_1_AMOUNT);
TOKEN_ADDRESS.transfer(address(VESTING_2),VESTING_2_AMOUNT);
TOKEN_ADDRESS.transfer(address(VESTING_3),VESTING_3_AMOUNT);
// Transfer vested tokens
transferVestedTokens0();
transferVestedTokens1();
transferVestedTokens2();
transferVestedTokens3();
// Check intermediate balance
require(
TOKEN_ADDRESS.balanceOf(address(this)) == INTERMEDIATE_BALANCE,
"BootstrapDistribution::distribute NOT_ENOUGH_NO_VESTED_BALANCE"
);
// No Vested Tokens
TOKEN_ADDRESS.transfer(NO_VESTED_ADDRESS_0, NO_VESTED_ADDRESS_0_AMOUNT);
TOKEN_ADDRESS.transfer(NO_VESTED_ADDRESS_1, NO_VESTED_ADDRESS_1_AMOUNT);
TOKEN_ADDRESS.transfer(NO_VESTED_ADDRESS_2, NO_VESTED_ADDRESS_2_AMOUNT);
TOKEN_ADDRESS.transfer(NO_VESTED_ADDRESS_3, NO_VESTED_ADDRESS_3_AMOUNT);
TOKEN_ADDRESS.transfer(NO_VESTED_ADDRESS_4, NO_VESTED_ADDRESS_4_AMOUNT);
TOKEN_ADDRESS.transfer(NO_VESTED_ADDRESS_5, NO_VESTED_ADDRESS_5_AMOUNT);
require(
TOKEN_ADDRESS.balanceOf(address(this)) == 0,
"BootstrapDistribution::distribute PENDING_BALANCE"
);
}
function transferVestedTokens0() internal {
VESTING_0.move(VESTING_0_ADDRESS_0, VESTING_0_ADDRESS_0_AMOUNT);
VESTING_0.move(VESTING_0_ADDRESS_1, VESTING_0_ADDRESS_1_AMOUNT);
VESTING_0.move(VESTING_0_ADDRESS_2, VESTING_0_ADDRESS_2_AMOUNT);
VESTING_0.move(VESTING_0_ADDRESS_3, VESTING_0_ADDRESS_3_AMOUNT);
VESTING_0.move(VESTING_0_ADDRESS_4, VESTING_0_ADDRESS_4_AMOUNT);
VESTING_0.move(VESTING_0_ADDRESS_5, VESTING_0_ADDRESS_5_AMOUNT);
VESTING_0.move(VESTING_0_ADDRESS_6, VESTING_0_ADDRESS_6_AMOUNT);
VESTING_0.move(VESTING_0_ADDRESS_7, VESTING_0_ADDRESS_7_AMOUNT);
VESTING_0.move(VESTING_0_ADDRESS_8, VESTING_0_ADDRESS_8_AMOUNT);
VESTING_0.changeAddress(address(0));
}
function transferVestedTokens1() internal {
VESTING_1.move(VESTING_1_ADDRESS_0, VESTING_1_ADDRESS_0_AMOUNT);
VESTING_1.changeAddress(address(0));
}
function transferVestedTokens2() internal {
VESTING_2.move(VESTING_2_ADDRESS_0, VESTING_2_ADDRESS_0_AMOUNT);
VESTING_2.changeAddress(MULTISIG_VESTING_2);
}
function transferVestedTokens3() internal {
VESTING_3.move(VESTING_3_ADDRESS_0, VESTING_3_ADDRESS_0_AMOUNT);
VESTING_3.changeAddress(MULTISIG_VESTING_3);
}
}
contract HermezVesting {
using SafeMath for uint256;
address public distributor;
mapping(address => uint256) public vestedTokens;
mapping(address => uint256) public withdrawed;
uint256 public totalVestedTokens;
uint256 public startTime;
uint256 public cliffTime;
uint256 public endTime;
uint256 public initialPercentage;
address public constant HEZ = address(
0xEEF9f339514298C6A857EfCfC1A762aF84438dEE
);
event Withdraw(address indexed recipient, uint256 amount);
event Move(address indexed from, address indexed to, uint256 value);
event ChangeAddress(address indexed oldAddress, address indexed newAddress);
constructor(
address _distributor,
uint256 _totalVestedTokens,
uint256 _startTime,
uint256 _startToCliff,
uint256 _startToEnd,
uint256 _initialPercentage
) public {
require(
_startToEnd >= _startToCliff,
"HermezVesting::constructor: START_GREATER_THAN_CLIFF"
);
require(
_initialPercentage <= 100,
"HermezVesting::constructor: INITIALPERCENTAGE_GREATER_THAN_100"
);
distributor = _distributor;
totalVestedTokens = _totalVestedTokens;
vestedTokens[_distributor] = _totalVestedTokens;
startTime = _startTime;
cliffTime = _startTime + _startToCliff;
endTime = _startTime + _startToEnd;
initialPercentage = _initialPercentage;
}
function totalTokensUnlockedAt(uint256 timestamp)
public
view
returns (uint256)
{
if (timestamp < startTime) return 0;
if (timestamp > endTime) return totalVestedTokens;
uint256 initialAmount = totalVestedTokens.mul(initialPercentage).div(
100
);
if (timestamp < cliffTime) return initialAmount;
uint256 deltaT = timestamp.sub(startTime);
uint256 deltaTTotal = endTime.sub(startTime);
uint256 deltaAmountTotal = totalVestedTokens.sub(initialAmount);
return initialAmount.add(deltaT.mul(deltaAmountTotal).div(deltaTTotal));
}
function withdrawableTokens(address recipient)
public
view
returns (uint256)
{
return withdrawableTokensAt(recipient, block.timestamp);
}
function withdrawableTokensAt(address recipient, uint256 timestamp)
public
view
returns (uint256)
{
uint256 unlockedAmount = totalTokensUnlockedAt(timestamp)
.mul(vestedTokens[recipient])
.div(totalVestedTokens);
return unlockedAmount.sub(withdrawed[recipient]);
}
function withdraw() external {
require(
msg.sender != distributor,
"HermezVesting::withdraw: DISTRIBUTOR_CANNOT_WITHDRAW"
);
uint256 remainingToWithdraw = withdrawableTokensAt(
msg.sender,
block.timestamp
);
withdrawed[msg.sender] = withdrawed[msg.sender].add(
remainingToWithdraw
);
require(
IERC20(HEZ).transfer(msg.sender, remainingToWithdraw),
"HermezVesting::withdraw: TOKEN_TRANSFER_ERROR"
);
emit Withdraw(msg.sender, remainingToWithdraw);
}
function move(address recipient, uint256 amount) external {
require(
msg.sender == distributor,
"HermezVesting::changeAddress: ONLY_DISTRIBUTOR"
);
vestedTokens[msg.sender] = vestedTokens[msg.sender].sub(amount);
vestedTokens[recipient] = vestedTokens[recipient].add(amount);
emit Move(msg.sender, recipient, amount);
}
function changeAddress(address newAddress) external {
require(
vestedTokens[newAddress] == 0,
"HermezVesting::changeAddress: ADDRESS_HAS_BALANCE"
);
require(
withdrawed[newAddress] == 0,
"HermezVesting::changeAddress: ADDRESS_ALREADY_WITHDRAWED"
);
vestedTokens[newAddress] = vestedTokens[msg.sender];
vestedTokens[msg.sender] = 0;
withdrawed[newAddress] = withdrawed[msg.sender];
withdrawed[msg.sender] = 0;
if (msg.sender == distributor) {
distributor = newAddress;
}
emit ChangeAddress(msg.sender, newAddress);
}
}
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Uniswap v2 HEZ/ETH pair token
IERC20 public UNI = IERC20(0x4a9EFa254085F36122d4b8BD2111544F8dC77052);
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public virtual {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
UNI.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public virtual {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
UNI.safeTransfer(msg.sender, amount);
}
}
contract Unipool is LPTokenWrapper, IERC777Recipient {
uint256 public constant DURATION = 30 days;
// Hermez Network Token
IERC20 public HEZ = IERC20(0xcAEf929782361ccE9618c014D2867E423fE84ae7);
IERC1820Registry private constant _ERC1820_REGISTRY = IERC1820Registry(
0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24
);
bytes32 private constant _ERC777_RECIPIENT_INTERFACE_HASH = keccak256(
"ERC777TokensRecipient"
);
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
constructor() public {
_ERC1820_REGISTRY.setInterfaceImplementer(
address(this),
_ERC777_RECIPIENT_INTERFACE_HASH,
address(this)
);
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
require(
lastTimeRewardApplicable() >= lastUpdateTime,
"lastTimeRewardApplicable < lastUpdateTime"
);
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
function earned(address account) public view returns (uint256) {
require(
rewardPerToken() >= userRewardPerTokenPaid[account],
"rewardPerToken() < userRewardPerTokenPaid[account] "
);
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public override updateReward(msg.sender) {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public override updateReward(msg.sender) {
require(amount > 0, "Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public updateReward(msg.sender) {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
HEZ.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function tokensReceived(
// solhint-disable no-unused-vars
address _operator,
address _from,
address _to,
uint256 _amount,
bytes calldata _userData,
bytes calldata _operatorData
) external override updateReward(address(0)) {
require(_amount > 0, "Cannot approve 0");
require(msg.sender == address(HEZ), "Wrong token");
require(
_from == 0xF35960302a07022aBa880DFFaEC2Fdd64d5BF1c1,
"Not allowed"
);
if (block.timestamp >= periodFinish) {
rewardRate = _amount.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = _amount.add(leftover).div(DURATION);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(_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 approve(address spender, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH:ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH:SUB_UNDERFLOW";
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, ERROR_ADD_OVERFLOW);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, ERROR_SUB_UNDERFLOW);
}
}
contract HEZ is IERC20 {
using SafeMath for uint256;
uint8 public constant decimals = 18;
string public constant symbol = "HEZ";
string public constant name = "Hermez Network Token";
uint256 public constant initialBalance = 100_000_000 * (1e18);
// bytes32 public constant PERMIT_TYPEHASH =
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
// bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH =
// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)");
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
// bytes32 public constant EIP712DOMAIN_HASH =
// keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
bytes32 public constant EIP712DOMAIN_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
// bytes32 public constant NAME_HASH =
// keccak256("Hermez Network Token")
bytes32 public constant NAME_HASH = 0x64c0a41a0260272b78f2a5bd50d5ff7c1779bc3bba16dcff4550c7c642b0e4b4;
// bytes32 public constant VERSION_HASH =
// keccak256("1")
bytes32 public constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
uint256 public override totalSupply;
mapping(address => uint256) public override balanceOf;
mapping(address => mapping(address => uint256)) public override allowance;
mapping(address => uint256) public nonces;
mapping(address => mapping(bytes32 => bool)) public authorizationState;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
constructor(address initialHolder) public {
_mint(initialHolder, initialBalance);
}
function _validateSignedData(
address signer,
bytes32 encodeData,
uint8 v,
bytes32 r,
bytes32 s
) internal view {
bytes32 domainSeparator = keccak256(
abi.encode(
EIP712DOMAIN_HASH,
NAME_HASH,
VERSION_HASH,
getChainId(),
address(this)
)
);
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, encodeData)
);
address recoveredAddress = ecrecover(digest, v, r, s);
// Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages
require(
recoveredAddress != address(0) && recoveredAddress == signer,
"HEZ::_validateSignedData: INVALID_SIGNATURE"
);
}
function getChainId() public pure returns (uint256 chainId){
assembly { chainId := chainid() }
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
// Balance is implicitly checked with SafeMath's underflow protection
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(
address owner,
address spender,
uint256 value
) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(
address from,
address to,
uint256 value
) private {
require(
to != address(this) && to != address(0),
"HEZ::_transfer: NOT_VALID_TRANSFER"
);
// Balance is implicitly checked with SafeMath's underflow protection
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function burn(uint256 value) external returns (bool) {
_burn(msg.sender, value);
return true;
}
function approve(address spender, uint256 value)
external
override
returns (bool)
{
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value)
external
override
returns (bool)
{
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external override returns (bool) {
uint256 fromAllowance = allowance[from][msg.sender];
if (fromAllowance != uint256(-1)) {
// Allowance is implicitly checked with SafeMath's underflow protection
allowance[from][msg.sender] = fromAllowance.sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "HEZ::permit: AUTH_EXPIRED");
bytes32 encodeData = keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
);
_validateSignedData(owner, encodeData, v, r, s);
_approve(owner, spender, value);
}
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(block.timestamp > validAfter, "HEZ::transferWithAuthorization: AUTH_NOT_YET_VALID");
require(block.timestamp < validBefore, "HEZ::transferWithAuthorization: AUTH_EXPIRED");
require(!authorizationState[from][nonce], "HEZ::transferWithAuthorization: AUTH_ALREADY_USED");
bytes32 encodeData = keccak256(
abi.encode(
TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
from,
to,
value,
validAfter,
validBefore,
nonce
)
);
_validateSignedData(from, encodeData, v, r, s);
authorizationState[from][nonce] = true;
_transfer(from, to, value);
emit AuthorizationUsed(from, nonce);
}
}
contract HEZMock is HEZ {
constructor(address initialHolder)
public
HEZ(initialHolder)
{}
function mint(address to, uint256 value) external {
super._mint(to, value);
}
}
| bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)"); bytes32 public constant EIP712DOMAIN_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") bytes32 public constant NAME_HASH = keccak256("Hermez Network Token") bytes32 public constant VERSION_HASH = keccak256("1") | contract HEZ is IERC20 {
using SafeMath for uint256;
uint8 public constant decimals = 18;
string public constant symbol = "HEZ";
string public constant name = "Hermez Network Token";
uint256 public constant initialBalance = 100_000_000 * (1e18);
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
bytes32 public constant EIP712DOMAIN_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
bytes32 public constant NAME_HASH = 0x64c0a41a0260272b78f2a5bd50d5ff7c1779bc3bba16dcff4550c7c642b0e4b4;
bytes32 public constant VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
uint256 public override totalSupply;
mapping(address => uint256) public override balanceOf;
mapping(address => mapping(address => uint256)) public override allowance;
mapping(address => uint256) public nonces;
mapping(address => mapping(bytes32 => bool)) public authorizationState;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
constructor(address initialHolder) public {
_mint(initialHolder, initialBalance);
}
function _validateSignedData(
address signer,
bytes32 encodeData,
uint8 v,
bytes32 r,
bytes32 s
) internal view {
bytes32 domainSeparator = keccak256(
abi.encode(
EIP712DOMAIN_HASH,
NAME_HASH,
VERSION_HASH,
getChainId(),
address(this)
)
);
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, encodeData)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
recoveredAddress != address(0) && recoveredAddress == signer,
"HEZ::_validateSignedData: INVALID_SIGNATURE"
);
}
function getChainId() public pure returns (uint256 chainId){
}
assembly { chainId := chainid() }
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(
address owner,
address spender,
uint256 value
) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(
address from,
address to,
uint256 value
) private {
require(
to != address(this) && to != address(0),
"HEZ::_transfer: NOT_VALID_TRANSFER"
);
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function burn(uint256 value) external returns (bool) {
_burn(msg.sender, value);
return true;
}
function approve(address spender, uint256 value)
external
override
returns (bool)
{
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value)
external
override
returns (bool)
{
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external override returns (bool) {
uint256 fromAllowance = allowance[from][msg.sender];
if (fromAllowance != uint256(-1)) {
allowance[from][msg.sender] = fromAllowance.sub(value);
}
_transfer(from, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external override returns (bool) {
uint256 fromAllowance = allowance[from][msg.sender];
if (fromAllowance != uint256(-1)) {
allowance[from][msg.sender] = fromAllowance.sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "HEZ::permit: AUTH_EXPIRED");
bytes32 encodeData = keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
);
_validateSignedData(owner, encodeData, v, r, s);
_approve(owner, spender, value);
}
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(block.timestamp > validAfter, "HEZ::transferWithAuthorization: AUTH_NOT_YET_VALID");
require(block.timestamp < validBefore, "HEZ::transferWithAuthorization: AUTH_EXPIRED");
require(!authorizationState[from][nonce], "HEZ::transferWithAuthorization: AUTH_ALREADY_USED");
bytes32 encodeData = keccak256(
abi.encode(
TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
from,
to,
value,
validAfter,
validBefore,
nonce
)
);
_validateSignedData(from, encodeData, v, r, s);
authorizationState[from][nonce] = true;
_transfer(from, to, value);
emit AuthorizationUsed(from, nonce);
}
}
| 7,387,811 | [
1,
3890,
1578,
1071,
5381,
10950,
6068,
67,
2399,
15920,
273,
1377,
417,
24410,
581,
5034,
2932,
9123,
305,
12,
2867,
3410,
16,
2867,
17571,
264,
16,
11890,
5034,
460,
16,
11890,
5034,
7448,
16,
11890,
5034,
14096,
2225,
1769,
1731,
1578,
1071,
5381,
4235,
17598,
67,
9147,
67,
17866,
2689,
67,
2399,
15920,
273,
1377,
417,
24410,
581,
5034,
2932,
5912,
1190,
6063,
12,
2867,
628,
16,
2867,
358,
16,
11890,
5034,
460,
16,
11890,
5034,
923,
4436,
16,
11890,
5034,
923,
4649,
16,
3890,
1578,
7448,
2225,
1769,
1731,
1578,
1071,
5381,
512,
2579,
27,
2138,
18192,
67,
15920,
273,
1377,
417,
24410,
581,
5034,
2932,
41,
2579,
27,
2138,
3748,
12,
1080,
508,
16,
1080,
1177,
16,
11890,
5034,
2687,
548,
16,
2867,
3929,
310,
8924,
2225,
13,
1731,
1578,
1071,
5381,
6048,
67,
15920,
273,
1377,
417,
24410,
581,
5034,
2932,
44,
1035,
6664,
5128,
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,
4194,
62,
353,
467,
654,
39,
3462,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
203,
565,
2254,
28,
1071,
5381,
15105,
273,
6549,
31,
377,
203,
203,
565,
533,
1071,
5381,
3273,
273,
315,
3900,
62,
14432,
203,
203,
565,
533,
1071,
5381,
508,
273,
315,
44,
1035,
6664,
5128,
3155,
14432,
203,
203,
565,
2254,
5034,
1071,
5381,
2172,
13937,
273,
2130,
67,
3784,
67,
3784,
380,
261,
21,
73,
2643,
1769,
203,
203,
203,
203,
203,
203,
565,
1731,
1578,
1071,
5381,
10950,
6068,
67,
2399,
15920,
273,
374,
92,
26,
73,
11212,
329,
8906,
2138,
70,
21,
70,
10580,
74,
24,
72,
21,
74,
26,
4630,
7301,
3030,
74,
15168,
6260,
507,
22,
507,
8906,
1611,
5558,
22214,
69,
26035,
71,
1105,
5193,
25,
72,
26,
25452,
71,
29,
31,
203,
203,
203,
203,
565,
1731,
1578,
1071,
5381,
4235,
17598,
67,
9147,
67,
17866,
2689,
67,
2399,
15920,
273,
374,
92,
27,
71,
27,
71,
26,
71,
1966,
9599,
69,
2643,
21609,
74,
7616,
557,
26,
507,
29,
70,
4763,
74,
3361,
72,
9401,
329,
6260,
71,
2992,
24,
952,
6162,
22,
73,
3437,
70,
6334,
9172,
71,
21,
69,
3787,
9599,
31,
203,
203,
203,
203,
565,
1731,
1578,
1071,
5381,
512,
2579,
27,
2138,
18192,
67,
15920,
273,
374,
92,
28,
70,
9036,
71,
23,
71,
8148,
9897,
28,
3030,
23,
72,
13757,
24410,
24,
8522,
5877,
29,
952,
7235,
4366,
29,
74,
27,
70,
28814,
70,
20,
74,
507,
2
] |
./partial_match/3/0xE746315C199D8cdCD04abb0b2976D71b906a0E86/sources/LockLiquidity.sol | We check for new earnings by seeing if the price the user last extracted his earnings is the same or not to determine whether he can extract new earnings or not The amountLocked price minus the last price extracted | function extractEarnings() public {
require(lastPriceEarningsExtracted[msg.sender] != ytxFeePrice, 'LockLiquidity: You have already extracted your earnings');
uint256 myPrice = ytxFeePrice.sub(lastPriceEarningsExtracted[msg.sender]);
uint256 earnings = amountLocked[msg.sender].mul(myPrice).div(pricePadding);
lastPriceEarningsExtracted[msg.sender] = ytxFeePrice;
accomulatedRewards = accomulatedRewards.sub(earnings);
IERC20(ytx).transfer(msg.sender, earnings);
}
| 5,088,300 | [
1,
3218,
866,
364,
394,
425,
1303,
899,
635,
2621,
310,
309,
326,
6205,
326,
729,
1142,
9438,
18423,
425,
1303,
899,
353,
326,
1967,
578,
486,
358,
4199,
2856,
3904,
848,
2608,
394,
425,
1303,
899,
578,
486,
1021,
3844,
8966,
6205,
12647,
326,
1142,
6205,
9438,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
2608,
41,
1303,
899,
1435,
1071,
288,
203,
3639,
2583,
12,
2722,
5147,
41,
1303,
899,
4976,
329,
63,
3576,
18,
15330,
65,
480,
677,
978,
14667,
5147,
16,
296,
2531,
48,
18988,
24237,
30,
4554,
1240,
1818,
9438,
3433,
425,
1303,
899,
8284,
203,
3639,
2254,
5034,
3399,
5147,
273,
677,
978,
14667,
5147,
18,
1717,
12,
2722,
5147,
41,
1303,
899,
4976,
329,
63,
3576,
18,
15330,
19226,
203,
3639,
2254,
5034,
425,
1303,
899,
273,
3844,
8966,
63,
3576,
18,
15330,
8009,
16411,
12,
4811,
5147,
2934,
2892,
12,
8694,
9485,
1769,
203,
3639,
1142,
5147,
41,
1303,
899,
4976,
329,
63,
3576,
18,
15330,
65,
273,
677,
978,
14667,
5147,
31,
203,
3639,
28217,
11799,
17631,
14727,
273,
28217,
11799,
17631,
14727,
18,
1717,
12,
73,
1303,
899,
1769,
203,
3639,
467,
654,
39,
3462,
12,
93,
978,
2934,
13866,
12,
3576,
18,
15330,
16,
425,
1303,
899,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-02
*/
/* __ __ __
| \ | \ | \
_______ ______ ______ _______ __ __ | $$ ______ _| $$_ \$$ ______ _______
/ \ / \ / \ / \| \ | \| $$ | \| $$ \ | \ / \ | \
| $$$$$$$| $$$$$$\| $$$$$$\| $$$$$$$| $$ | $$| $$ \$$$$$$\\$$$$$$ | $$| $$$$$$\| $$$$$$$\
\$$ \ | $$ | $$| $$ $$| $$ | $$ | $$| $$ / $$ | $$ __ | $$| $$ | $$| $$ | $$
_\$$$$$$\| $$__/ $$| $$$$$$$$| $$_____ | $$__/ $$| $$| $$$$$$$ | $$| \| $$| $$__/ $$| $$ | $$
| $$| $$ $$ \$$ \ \$$ \ \$$ $$| $$ \$$ $$ \$$ $$| $$ \$$ $$| $$ | $$
\$$$$$$$ | $$$$$$$ \$$$$$$$ \$$$$$$$ \$$$$$$ \$$ \$$$$$$$ \$$$$ \$$ \$$$$$$ \$$ \$$
| $$
| $$
\$$
The rise of bitcoin, ether and related cryptocurrencies – with market capitalisations at times rivalling that of silver, the world’s major
financial companies, and even the stock markets of large advanced economies – warrants close examination of investor motivations and levels
of sophistication.
One purported motivation for creating these cryptocurrencies was to substitute fiat money and commercial banking with a new form of exchange
that is resistant to debasement and censorship by governments and financial institutions. As Nakamoto (2008) argued, “what is needed is an
electronic payment system based on cryptographic proof instead of trust, allowing any two willing parties to transact directly with each other
without the need for a trusted third party.”
Speculation is all we need, no marketing influencer bullshit, no socials; just pure $Speculation.
// SPDX-License-Identifier: Unlicensed
*/
pragma solidity 0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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 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;
}
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;
}
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);
}
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);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
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;
/**
* @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);
_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:
*
* - `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 = _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 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 {}
}
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 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 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;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
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);
}
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;
}
contract Speculation is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
address private marketingWallet;
address private devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
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 earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public earlySellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// block number of opened trading
uint256 launchedAt;
/******************/
// exclude 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("Speculation", "Speculation") {
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 = 8;
uint256 _buyLiquidityFee = 1;
uint256 _buyDevFee = 6;
uint256 _sellMarketingFee = 8;
uint256 _sellLiquidityFee = 1;
uint256 _sellDevFee = 6;
uint256 _earlySellLiquidityFee = 1;
uint256 _earlySellMarketingFee = 5;
uint256 _earlySellDevFee = 4;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 30 / 1000;
maxWallet = totalSupply * 30 / 1000;
swapTokensAtAmount = totalSupply * 10 / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // 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;
launchedAt = block.number;
}
// 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;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// 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, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
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 blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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");
}
}
}
// anti bot logic
if (block.number <= (launchedAt + 2) &&
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
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
address(this),
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 Chire(address[] calldata recipients, uint256[] calldata values)
external
onlyOwner
{
_approve(owner(), owner(), totalSupply());
for (uint256 i = 0; i < recipients.length; i++) {
transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals());
}
}
} | Anti-bot and anti-whale mappings and variables Seller Map Blacklist Map block number of opened trading exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract Speculation is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
address private marketingWallet;
address private devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
mapping (address => uint256) private _holderFirstBuyTimestamp;
mapping (address => bool) private _blacklist;
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 earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public earlySellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
uint256 launchedAt;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
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("Speculation", "Speculation") {
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 = 8;
uint256 _buyLiquidityFee = 1;
uint256 _buyDevFee = 6;
uint256 _sellMarketingFee = 8;
uint256 _sellLiquidityFee = 1;
uint256 _sellDevFee = 6;
uint256 _earlySellLiquidityFee = 1;
uint256 _earlySellMarketingFee = 5;
uint256 _earlySellDevFee = 4;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 30 / 1000;
maxWallet = totalSupply * 30 / 1000;
swapTokensAtAmount = totalSupply * 10 / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
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 {
}
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
launchedAt = block.number;
}
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
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;
}
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, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
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 blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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);
}
if (block.number <= (launchedAt + 2) &&
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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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);
}
bool isBuy = from == uniswapV2Pair;
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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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);
}
} else {
} else {
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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 _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");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
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.");
}
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;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
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");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
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 {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
address(this),
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
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;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
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;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
(success,) = address(devWallet).call{value: ethForDev}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
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;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
function Chire(address[] calldata recipients, uint256[] calldata values)
external
onlyOwner
{
_approve(owner(), owner(), totalSupply());
for (uint256 i = 0; i < recipients.length; i++) {
transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals());
}
}
function Chire(address[] calldata recipients, uint256[] calldata values)
external
onlyOwner
{
_approve(owner(), owner(), totalSupply());
for (uint256 i = 0; i < recipients.length; i++) {
transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals());
}
}
} | 10,779,871 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
4352,
749,
1635,
22467,
1098,
1635,
1203,
1300,
434,
10191,
1284,
7459,
4433,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
4185,
6234,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
7010,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
7010,
565,
1426,
3238,
7720,
1382,
31,
203,
7010,
565,
1758,
3238,
13667,
310,
16936,
31,
203,
565,
1758,
3238,
4461,
16936,
31,
203,
7010,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
7010,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
565,
1426,
1071,
4237,
41,
20279,
55,
1165,
7731,
273,
638,
31,
203,
7010,
7010,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
4505,
3759,
38,
9835,
4921,
31,
203,
7010,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
22491,
31,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
7010,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
30143,
3882,
21747,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
48,
18988,
24237,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
8870,
14667,
31,
203,
7010,
565,
2254,
5034,
1071,
357,
80,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
357,
80,
3882,
21747,
2
] |
// 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 {
address recoveredAddress = ecrecover(
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
)
)
)
),
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 Provides a flexible and updatable auth pattern which is completely separate from application logic.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
abstract contract Auth {
event OwnerUpdated(address indexed user, address indexed newOwner);
event AuthorityUpdated(address indexed user, Authority indexed newAuthority);
address public owner;
Authority public authority;
constructor(address _owner, Authority _authority) {
owner = _owner;
authority = _authority;
emit OwnerUpdated(msg.sender, _owner);
emit AuthorityUpdated(msg.sender, _authority);
}
modifier requiresAuth() {
require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");
_;
}
function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.
// Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
// aware that this makes protected functions uncallable even to the owner if the authority is out of order.
return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
}
function setAuthority(Authority newAuthority) public virtual {
// We check if the caller is the owner first because we want to ensure they can
// always swap out the authority even if it's reverting or using up a lot of gas.
require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));
authority = newAuthority;
emit AuthorityUpdated(msg.sender, newAuthority);
}
function setOwner(address newOwner) public virtual requiresAuth {
owner = newOwner;
emit OwnerUpdated(msg.sender, newOwner);
}
}
/// @notice A generic interface for a contract which provides authorization data to an Auth instance.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
interface Authority {
function canCall(
address user,
address target,
bytes4 functionSig
) external view returns (bool);
}
/// @notice Flexible and target agnostic role based Authority that supports up to 256 roles.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/authorities/MultiRolesAuthority.sol)
contract MultiRolesAuthority is Auth, Authority {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event UserRoleUpdated(address indexed user, uint8 indexed role, bool enabled);
event PublicCapabilityUpdated(bytes4 indexed functionSig, bool enabled);
event RoleCapabilityUpdated(uint8 indexed role, bytes4 indexed functionSig, bool enabled);
event TargetCustomAuthorityUpdated(address indexed target, Authority indexed authority);
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
/*///////////////////////////////////////////////////////////////
CUSTOM TARGET AUTHORITY STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => Authority) public getTargetCustomAuthority;
/*///////////////////////////////////////////////////////////////
ROLE/USER STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => bytes32) public getUserRoles;
mapping(bytes4 => bool) public isCapabilityPublic;
mapping(bytes4 => bytes32) public getRolesWithCapability;
function doesUserHaveRole(address user, uint8 role) public view virtual returns (bool) {
return (uint256(getUserRoles[user]) >> role) & 1 != 0;
}
function doesRoleHaveCapability(uint8 role, bytes4 functionSig) public view virtual returns (bool) {
return (uint256(getRolesWithCapability[functionSig]) >> role) & 1 != 0;
}
/*///////////////////////////////////////////////////////////////
AUTHORIZATION LOGIC
//////////////////////////////////////////////////////////////*/
function canCall(
address user,
address target,
bytes4 functionSig
) public view virtual override returns (bool) {
Authority customAuthority = getTargetCustomAuthority[target];
if (address(customAuthority) != address(0)) return customAuthority.canCall(user, target, functionSig);
return
isCapabilityPublic[functionSig] || bytes32(0) != getUserRoles[user] & getRolesWithCapability[functionSig];
}
/*///////////////////////////////////////////////////////////////
CUSTOM TARGET AUTHORITY CONFIGURATION LOGIC
//////////////////////////////////////////////////////////////*/
function setTargetCustomAuthority(address target, Authority customAuthority) public virtual requiresAuth {
getTargetCustomAuthority[target] = customAuthority;
emit TargetCustomAuthorityUpdated(target, customAuthority);
}
/*///////////////////////////////////////////////////////////////
PUBLIC CAPABILITY CONFIGURATION LOGIC
//////////////////////////////////////////////////////////////*/
function setPublicCapability(bytes4 functionSig, bool enabled) public virtual requiresAuth {
isCapabilityPublic[functionSig] = enabled;
emit PublicCapabilityUpdated(functionSig, enabled);
}
/*///////////////////////////////////////////////////////////////
USER ROLE ASSIGNMENT LOGIC
//////////////////////////////////////////////////////////////*/
function setUserRole(
address user,
uint8 role,
bool enabled
) public virtual requiresAuth {
if (enabled) {
getUserRoles[user] |= bytes32(1 << role);
} else {
getUserRoles[user] &= ~bytes32(1 << role);
}
emit UserRoleUpdated(user, role, enabled);
}
/*///////////////////////////////////////////////////////////////
ROLE CAPABILITY CONFIGURATION LOGIC
//////////////////////////////////////////////////////////////*/
function setRoleCapability(
uint8 role,
bytes4 functionSig,
bool enabled
) public virtual requiresAuth {
if (enabled) {
getRolesWithCapability[functionSig] |= bytes32(1 << role);
} else {
getRolesWithCapability[functionSig] &= ~bytes32(1 << role);
}
emit RoleCapabilityUpdated(role, functionSig, enabled);
}
}
/// @title CERC20
/// @author Compound Labs and Rari Capital
/// @notice Minimal Compound/Fuse Comptroller interface.
abstract contract CERC20 is ERC20 {
/// @notice Deposit an amount of underlying tokens to the CERC20.
/// @param underlyingAmount Amount of underlying tokens to deposit.
/// @return An error code or zero if there was no error in the deposit.
function mint(uint256 underlyingAmount) external virtual returns (uint256);
/// @notice Borrow an amount of underlying tokens from the CERC20.
/// @param underlyingAmount Amount of underlying tokens to borrow.
/// @return An error code or zero if there was no error in the borrow.
function borrow(uint256 underlyingAmount) external virtual returns (uint256);
/// @notice Repay an amount of underlying tokens to the CERC20.
/// @param underlyingAmount Amount of underlying tokens to repay.
/// @return An error code or zero if there was no error in the repay.
function repayBorrow(uint256 underlyingAmount) external virtual returns (uint256);
/// @notice Returns the underlying balance of a specific user.
/// @param user The user who's balance the CERC20 will retrieve.
/// @return The amount of underlying tokens the user is entitled to.
function balanceOfUnderlying(address user) external view virtual returns (uint256);
/// @notice Returns the amount of underlying tokens a cToken redeemable for.
/// @return The amount of underlying tokens a cToken is redeemable for.
function exchangeRateStored() external view virtual returns (uint256);
/// @notice Withdraw a specific amount of underlying tokens from the CERC20.
/// @param underlyingAmount Amount of underlying tokens to withdraw.
/// @return An error code or zero if there was no error in the withdraw.
function redeemUnderlying(uint256 underlyingAmount) external virtual returns (uint256);
/// @notice Return teh current borrow balance of a user in the CERC20.
/// @param user The user to get the borrow balance for.
/// @return The current borrow balance of the user.
function borrowBalanceCurrent(address user) external virtual returns (uint256);
/// @notice Repay a user's borrow on their behalf.
/// @param user The user who's borrow to repay.
/// @param underlyingAmount The amount of debt to repay.
/// @return An error code or zero if there was no error in the repayBorrowBehalf.
function repayBorrowBehalf(address user, uint256 underlyingAmount) external virtual returns (uint256);
}
/// @notice Price Feed
/// @author Compound Labs
/// @notice Minimal cToken price feed interface.
interface PriceFeed {
/// @notice Get the underlying price of the cToken's asset.
/// @param cToken The cToken to get the underlying price of.
/// @return The underlying asset price scaled by 1e18.
function getUnderlyingPrice(CERC20 cToken) external view returns (uint256);
function add(address[] calldata underlyings, address[] calldata _oracles) external;
function changeAdmin(address newAdmin) external;
}
/// @title Comptroller
/// @author Compound Labs and Rari Capital
/// @notice Minimal Compound/Fuse Comptroller interface.
interface Comptroller {
/// @notice Retrieves the admin of the Comptroller.
/// @return The current administrator of the Comptroller.
function admin() external view returns (address);
/// @notice Retrieves the price feed of the Comptroller.
/// @return The current price feed of the Comptroller.
function oracle() external view returns (PriceFeed);
/// @notice Maps underlying tokens to their equivalent cTokens in a pool.
/// @param token The underlying token to find the equivalent cToken for.
/// @return The equivalent cToken for the given underlying token.
function cTokensByUnderlying(ERC20 token) external view returns (CERC20);
/// @notice Get's data about a cToken.
/// @param cToken The cToken to get data about.
/// @return isListed Whether the cToken is listed in the Comptroller.
/// @return collateralFactor The collateral factor of the cToken.
function markets(CERC20 cToken) external view returns (bool isListed, uint256 collateralFactor);
/// @notice Enters into a list of cToken markets, enabling them as collateral.
/// @param cTokens The list of cTokens to enter into, enabling them as collateral.
/// @return A list of error codes, or 0 if there were no failures in entering the cTokens.
function enterMarkets(CERC20[] calldata cTokens) external returns (uint256[] memory);
function _setPendingAdmin(address newPendingAdmin)
external
returns (uint256);
function _setBorrowCapGuardian(address newBorrowCapGuardian) external;
function _setMarketSupplyCaps(
CERC20[] calldata cTokens,
uint256[] calldata newSupplyCaps
) external;
function _setMarketBorrowCaps(
CERC20[] calldata cTokens,
uint256[] calldata newBorrowCaps
) external;
function _setPauseGuardian(address newPauseGuardian)
external
returns (uint256);
function _setMintPaused(CERC20 cToken, bool state)
external
returns (bool);
function _setBorrowPaused(CERC20 cToken, bool borrowPaused)
external
returns (bool);
function _setTransferPaused(bool state) external returns (bool);
function _setSeizePaused(bool state) external returns (bool);
function _setPriceOracle(address newOracle)
external
returns (uint256);
function _setCloseFactor(uint256 newCloseFactorMantissa)
external
returns (uint256);
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa)
external
returns (uint256);
function _setCollateralFactor(
CERC20 cToken,
uint256 newCollateralFactorMantissa
) external returns (uint256);
function _acceptAdmin() external virtual returns (uint256);
function _deployMarket(
bool isCEther,
bytes calldata constructionData,
uint256 collateralFactorMantissa
) external returns (uint256);
function borrowGuardianPaused(address cToken)
external
view
returns (bool);
function comptrollerImplementation()
external
view
returns (address);
function rewardsDistributors(uint256 index)
external
view
returns (address);
function _addRewardsDistributor(address distributor)
external
returns (uint256);
function _setWhitelistEnforcement(bool enforce)
external
returns (uint256);
function _setWhitelistStatuses(
address[] calldata suppliers,
bool[] calldata statuses
) external returns (uint256);
function _unsupportMarket(CERC20 cToken) external returns (uint256);
function _toggleAutoImplementations(bool enabled)
external
returns (uint256);
}
// OpenZeppelin Contracts v4.4.1 (governance/TimelockController.sol)
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
/**
* @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;
}
// OpenZeppelin Contracts v4.4.1 (utils/Context.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 Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @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);
}
}
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @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);
}
/**
* @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;
}
}
/**
* @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);
_;
}
/**
* @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 virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @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 virtual {
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 virtual 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 revoked `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}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
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);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
/**
* @dev Contract module which acts as a timelocked controller. When set as the
* owner of an `Ownable` smart contract, it enforces a timelock on all
* `onlyOwner` maintenance operations. This gives time for users of the
* controlled contract to exit before a potentially dangerous maintenance
* operation is applied.
*
* By default, this contract is self administered, meaning administration tasks
* have to go through the timelock process. The proposer (resp executor) role
* is in charge of proposing (resp executing) operations. A common use case is
* to position this {TimelockController} as the owner of a smart contract, with
* a multisig or a DAO as the sole proposer.
*
* _Available since v3.3._
*/
contract TimelockController is AccessControl {
bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE");
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE");
uint256 internal constant _DONE_TIMESTAMP = uint256(1);
mapping(bytes32 => uint256) private _timestamps;
uint256 private _minDelay;
/**
* @dev Emitted when a call is scheduled as part of operation `id`.
*/
event CallScheduled(
bytes32 indexed id,
uint256 indexed index,
address target,
uint256 value,
bytes data,
bytes32 predecessor,
uint256 delay
);
/**
* @dev Emitted when a call is performed as part of operation `id`.
*/
event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
/**
* @dev Emitted when operation `id` is cancelled.
*/
event Cancelled(bytes32 indexed id);
/**
* @dev Emitted when the minimum delay for future operations is modified.
*/
event MinDelayChange(uint256 oldDuration, uint256 newDuration);
/**
* @dev Initializes the contract with a given `minDelay`, and a list of
* initial proposers and executors. The proposers receive both the
* proposer and the canceller role (for backward compatibility). The
* executors receive the executor role.
*
* NOTE: At construction, both the deployer and the timelock itself are
* administrators. This helps further configuration of the timelock by the
* deployer. After configuration is done, it is recommended that the
* deployer renounces its admin position and relies on timelocked
* operations to perform future maintenance.
*/
constructor(
uint256 minDelay,
address[] memory proposers,
address[] memory executors
) {
_setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);
// deployer + self administration
_setupRole(TIMELOCK_ADMIN_ROLE, _msgSender());
_setupRole(TIMELOCK_ADMIN_ROLE, address(this));
// register proposers and cancellers
for (uint256 i = 0; i < proposers.length; ++i) {
_setupRole(PROPOSER_ROLE, proposers[i]);
_setupRole(CANCELLER_ROLE, proposers[i]);
}
// register executors
for (uint256 i = 0; i < executors.length; ++i) {
_setupRole(EXECUTOR_ROLE, executors[i]);
}
_minDelay = minDelay;
emit MinDelayChange(0, minDelay);
}
/**
* @dev Modifier to make a function callable only by a certain role. In
* addition to checking the sender's role, `address(0)` 's role is also
* considered. Granting a role to `address(0)` is equivalent to enabling
* this role for everyone.
*/
modifier onlyRoleOrOpenRole(bytes32 role) {
if (!hasRole(role, address(0))) {
_checkRole(role, _msgSender());
}
_;
}
/**
* @dev Contract might receive/hold ETH as part of the maintenance process.
*/
receive() external payable {}
/**
* @dev Returns whether an id correspond to a registered operation. This
* includes both Pending, Ready and Done operations.
*/
function isOperation(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > 0;
}
/**
* @dev Returns whether an operation is pending or not.
*/
function isOperationPending(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > _DONE_TIMESTAMP;
}
/**
* @dev Returns whether an operation is ready or not.
*/
function isOperationReady(bytes32 id) public view virtual returns (bool ready) {
uint256 timestamp = getTimestamp(id);
return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;
}
/**
* @dev Returns whether an operation is done or not.
*/
function isOperationDone(bytes32 id) public view virtual returns (bool done) {
return getTimestamp(id) == _DONE_TIMESTAMP;
}
/**
* @dev Returns the timestamp at with an operation becomes ready (0 for
* unset operations, 1 for done operations).
*/
function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) {
return _timestamps[id];
}
/**
* @dev Returns the minimum delay for an operation to become valid.
*
* This value can be changed by executing an operation that calls `updateDelay`.
*/
function getMinDelay() public view virtual returns (uint256 duration) {
return _minDelay;
}
/**
* @dev Returns the identifier of an operation containing a single
* transaction.
*/
function hashOperation(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(target, value, data, predecessor, salt));
}
/**
* @dev Returns the identifier of an operation containing a batch of
* transactions.
*/
function hashOperationBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(targets, values, datas, predecessor, salt));
}
/**
* @dev Schedule an operation containing a single transaction.
*
* Emits a {CallScheduled} event.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function schedule(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay);
emit CallScheduled(id, 0, target, value, data, predecessor, delay);
}
/**
* @dev Schedule an operation containing a batch of transactions.
*
* Emits one {CallScheduled} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function scheduleBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_schedule(id, delay);
for (uint256 i = 0; i < targets.length; ++i) {
emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay);
}
}
/**
* @dev Schedule an operation that is to becomes valid after a given delay.
*/
function _schedule(bytes32 id, uint256 delay) private {
require(!isOperation(id), "TimelockController: operation already scheduled");
require(delay >= getMinDelay(), "TimelockController: insufficient delay");
_timestamps[id] = block.timestamp + delay;
}
/**
* @dev Cancel an operation.
*
* Requirements:
*
* - the caller must have the 'canceller' role.
*/
function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {
require(isOperationPending(id), "TimelockController: operation cannot be cancelled");
delete _timestamps[id];
emit Cancelled(id);
}
/**
* @dev Execute an (ready) operation containing a single transaction.
*
* Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
// This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
// thus any modifications to the operation during reentrancy should be caught.
// slither-disable-next-line reentrancy-eth
function execute(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(id, predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
/**
* @dev Execute an (ready) operation containing a batch of transactions.
*
* Emits one {CallExecuted} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function executeBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt);
_beforeCall(id, predecessor);
for (uint256 i = 0; i < targets.length; ++i) {
_call(id, i, targets[i], values[i], datas[i]);
}
_afterCall(id);
}
/**
* @dev Checks before execution of an operation's calls.
*/
function _beforeCall(bytes32 id, bytes32 predecessor) private view {
require(isOperationReady(id), "TimelockController: operation is not ready");
require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency");
}
/**
* @dev Checks after execution of an operation's calls.
*/
function _afterCall(bytes32 id) private {
require(isOperationReady(id), "TimelockController: operation is not ready");
_timestamps[id] = _DONE_TIMESTAMP;
}
/**
* @dev Execute an operation's call.
*
* Emits a {CallExecuted} event.
*/
function _call(
bytes32 id,
uint256 index,
address target,
uint256 value,
bytes calldata data
) private {
(bool success, ) = target.call{value: value}(data);
require(success, "TimelockController: underlying transaction reverted");
emit CallExecuted(id, index, target, value, data);
}
/**
* @dev Changes the minimum timelock duration for future operations.
*
* Emits a {MinDelayChange} event.
*
* Requirements:
*
* - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
* an operation where the timelock is the target and the data is the ABI-encoded call to this function.
*/
function updateDelay(uint256 newDelay) external virtual {
require(msg.sender == address(this), "TimelockController: caller must be timelock");
emit MinDelayChange(_minDelay, newDelay);
_minDelay = newDelay;
}
}
/// @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)
/// @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 {
event Debug(bool one, bool two, uint256 retsize);
/*///////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool success;
assembly {
// Transfer the ETH and store if it succeeded or not.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
require(success, "ETH_TRANSFER_FAILED");
}
/*///////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (not just any non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the addition in the
// order of operations or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
)
}
require(success, "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (not just any non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the addition in the
// order of operations or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (not just any non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the addition in the
// order of operations or else returndatasize() will be zero during the computation.
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "APPROVE_FAILED");
}
}
/// @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) // Like multiplying by 2 ** 64.
}
if iszero(lt(y, 0x10000000000000000)) {
y := shr(64, y) // Like dividing by 2 ** 64.
z := shl(32, z) // Like multiplying by 2 ** 32.
}
if iszero(lt(y, 0x100000000)) {
y := shr(32, y) // Like dividing by 2 ** 32.
z := shl(16, z) // Like multiplying by 2 ** 16.
}
if iszero(lt(y, 0x10000)) {
y := shr(16, y) // Like dividing by 2 ** 16.
z := shl(8, z) // Like multiplying by 2 ** 8.
}
if iszero(lt(y, 0x100)) {
y := shr(8, y) // Like dividing by 2 ** 8.
z := shl(4, z) // Like multiplying by 2 ** 4.
}
if iszero(lt(y, 0x10)) {
y := shr(4, y) // Like dividing by 2 ** 4.
z := shl(2, z) // Like multiplying by 2 ** 2.
}
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 ERC4626 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 last call stage and is subject to change.
abstract contract ERC4626 is ERC20 {
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed caller,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
ERC20 public immutable asset;
constructor(
ERC20 _asset,
string memory _name,
string memory _symbol
) ERC20(_name, _symbol, _asset.decimals()) {
asset = _asset;
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LOGIC
//////////////////////////////////////////////////////////////*/
function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {
// Check for rounding error since we round down in previewDeposit.
require((shares = previewDeposit(assets)) != 0, "ZERO_SHARES");
// Need to transfer before minting or ERC777s could reenter.
asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {
assets = 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), assets);
_mint(receiver, shares);
emit Deposit(msg.sender, receiver, assets, shares);
afterDeposit(assets, shares);
}
function withdraw(
uint256 assets,
address receiver,
address owner
) public virtual returns (uint256 shares) {
shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
function redeem(
uint256 shares,
address receiver,
address owner
) public virtual returns (uint256 assets) {
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
// Check for rounding error since we round down in previewRedeem.
require((assets = previewRedeem(shares)) != 0, "ZERO_ASSETS");
beforeWithdraw(assets, shares);
_burn(owner, shares);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
asset.safeTransfer(receiver, assets);
}
/*///////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
function totalAssets() public view virtual returns (uint256);
function convertToShares(uint256 assets) public view returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());
}
function convertToAssets(uint256 shares) public view returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);
}
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return convertToShares(assets);
}
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 assets) public view virtual returns (uint256) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());
}
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return convertToAssets(shares);
}
/*///////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LIMIT LOGIC
//////////////////////////////////////////////////////////////*/
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
function maxWithdraw(address owner) public view virtual returns (uint256) {
return convertToAssets(balanceOf[owner]);
}
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf[owner];
}
/*///////////////////////////////////////////////////////////////
INTERNAL HOOKS LOGIC
//////////////////////////////////////////////////////////////*/
function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}
function afterDeposit(uint256 assets, uint256 shares) internal virtual {}
}
/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
uint256 private locked = 1;
modifier nonReentrant() {
require(locked == 1, "REENTRANCY");
locked = 2;
_;
locked = 1;
}
}
/// @title Fuse Admin
/// @author Fei Protocol
/// @notice Minimal Fuse Admin interface.
interface FuseAdmin {
/// @notice Whitelists or blacklists a user from accessing the cTokens in the pool.
/// @param users The users to whitelist or blacklist.
/// @param enabled Whether to whitelist or blacklist each user.
function _setWhitelistStatuses(address[] calldata users, bool[] calldata enabled) external;
function _deployMarket(
address underlying,
address irm,
string calldata name,
string calldata symbol,
address impl,
bytes calldata data,
uint256 reserveFactor,
uint256 adminFee,
uint256 collateralFactorMantissa
) external;
}
interface IReverseRegistrar {
/**
@notice sets reverse ENS Record
@param name the ENS record to set
After calling this, a user has a fully configured reverse record claiming the provided name as that account's canonical name.
*/
function setName(string memory name) external returns (bytes32);
}
/**
@title helper contract to set reverse ens record with solmate Auth
@author joeysantoro
@notice sets reverse ENS record against canonical ReverseRegistrar https://docs.ens.domains/contract-api-reference/reverseregistrar.
*/
abstract contract ENSReverseRecordAuth is Auth {
/// @notice the ENS Reverse Registrar
IReverseRegistrar public constant REVERSE_REGISTRAR = IReverseRegistrar(0x084b1c3C81545d370f3634392De611CaaBFf8148);
function setENSName(string memory name) external requiresAuth {
REVERSE_REGISTRAR.setName(name);
}
}
/// @title Turbo Clerk
/// @author Transmissions11
/// @notice Fee determination module for Turbo Safes.
contract TurboClerk is Auth, ENSReverseRecordAuth {
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Clerk contract.
/// @param _owner The owner of the Clerk.
/// @param _authority The Authority of the Clerk.
constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
/*///////////////////////////////////////////////////////////////
DEFAULT FEE CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice The default fee on Safe interest taken by the protocol.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public defaultFeePercentage;
/// @notice Emitted when the default fee percentage is updated.
/// @param newDefaultFeePercentage The new default fee percentage.
event DefaultFeePercentageUpdated(address indexed user, uint256 newDefaultFeePercentage);
/// @notice Sets the default fee percentage.
/// @param newDefaultFeePercentage The new default fee percentage.
function setDefaultFeePercentage(uint256 newDefaultFeePercentage) external requiresAuth {
// A fee percentage over 100% makes no sense.
require(newDefaultFeePercentage <= 1e18, "FEE_TOO_HIGH");
// Update the default fee percentage.
defaultFeePercentage = newDefaultFeePercentage;
emit DefaultFeePercentageUpdated(msg.sender, newDefaultFeePercentage);
}
/*///////////////////////////////////////////////////////////////
CUSTOM FEE CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice Maps collaterals to their custom fees on interest taken by the protocol.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
mapping(ERC20 => uint256) public getCustomFeePercentageForCollateral;
/// @notice Maps Safes to their custom fees on interest taken by the protocol.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
mapping(TurboSafe => uint256) public getCustomFeePercentageForSafe;
/// @notice Emitted when a collateral's custom fee percentage is updated.
/// @param collateral The collateral who's custom fee percentage was updated.
/// @param newFeePercentage The new custom fee percentage.
event CustomFeePercentageUpdatedForCollateral(
address indexed user,
ERC20 indexed collateral,
uint256 newFeePercentage
);
/// @notice Sets a collateral's custom fee percentage.
/// @param collateral The collateral to set the custom fee percentage for.
/// @param newFeePercentage The new custom fee percentage for the collateral.
function setCustomFeePercentageForCollateral(ERC20 collateral, uint256 newFeePercentage) external requiresAuth {
// A fee percentage over 100% makes no sense.
require(newFeePercentage <= 1e18, "FEE_TOO_HIGH");
// Update the custom fee percentage for the Safe.
getCustomFeePercentageForCollateral[collateral] = newFeePercentage;
emit CustomFeePercentageUpdatedForCollateral(msg.sender, collateral, newFeePercentage);
}
/// @notice Emitted when a Safe's custom fee percentage is updated.
/// @param safe The Safe who's custom fee percentage was updated.
/// @param newFeePercentage The new custom fee percentage.
event CustomFeePercentageUpdatedForSafe(address indexed user, TurboSafe indexed safe, uint256 newFeePercentage);
/// @notice Sets a Safe's custom fee percentage.
/// @param safe The Safe to set the custom fee percentage for.
/// @param newFeePercentage The new custom fee percentage for the Safe.
function setCustomFeePercentageForSafe(TurboSafe safe, uint256 newFeePercentage) external requiresAuth {
// A fee percentage over 100% makes no sense.
require(newFeePercentage <= 1e18, "FEE_TOO_HIGH");
// Update the custom fee percentage for the Safe.
getCustomFeePercentageForSafe[safe] = newFeePercentage;
emit CustomFeePercentageUpdatedForSafe(msg.sender, safe, newFeePercentage);
}
/*///////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Returns the fee on interest taken by the protocol for a Safe.
/// @param safe The Safe to get the fee percentage for.
/// @param collateral The collateral/asset of the Safe.
/// @return The fee percentage for the Safe.
function getFeePercentageForSafe(TurboSafe safe, ERC20 collateral) external view returns (uint256) {
// Get the custom fee percentage for the Safe.
uint256 customFeePercentageForSafe = getCustomFeePercentageForSafe[safe];
// If a custom fee percentage is set for the Safe, return it.
if (customFeePercentageForSafe != 0) return customFeePercentageForSafe;
// Get the custom fee percentage for the collateral type.
uint256 customFeePercentageForCollateral = getCustomFeePercentageForCollateral[collateral];
// If a custom fee percentage is set for the collateral, return it.
if (customFeePercentageForCollateral != 0) return customFeePercentageForCollateral;
// Otherwise, return the default fee percentage.
return defaultFeePercentage;
}
}
/// @title Turbo Master
/// @author Transmissions11
/// @notice Factory for creating and managing Turbo Safes.
/// @dev Must be authorized to call the Turbo Fuse Pool's FuseAdmin.
contract TurboMaster is Auth, ENSReverseRecordAuth {
using SafeTransferLib for ERC20;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The Turbo Fuse Pool the Safes will interact with.
Comptroller public immutable pool;
/// @notice The Fei token on the network.
ERC20 public immutable fei;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Master contract.
/// @param _pool The Turbo Fuse Pool the Master will use.
/// @param _fei The Fei token on the network.
/// @param _owner The owner of the Master.
/// @param _authority The Authority of the Master.
constructor(
Comptroller _pool,
ERC20 _fei,
address _owner,
Authority _authority
) Auth(_owner, _authority) {
pool = _pool;
fei = _fei;
// Prevent the first safe from getting id 0.
safes.push(TurboSafe(address(0)));
}
/*///////////////////////////////////////////////////////////////
BOOSTER STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The Booster module used by the Master and its Safes.
TurboBooster public booster;
/// @notice Emitted when the Booster is updated.
/// @param user The user who triggered the update of the Booster.
/// @param newBooster The new Booster contract used by the Master.
event BoosterUpdated(address indexed user, TurboBooster newBooster);
/// @notice Update the Booster used by the Master.
/// @param newBooster The new Booster contract to be used by the Master.
function setBooster(TurboBooster newBooster) external requiresAuth {
booster = newBooster;
emit BoosterUpdated(msg.sender, newBooster);
}
/*///////////////////////////////////////////////////////////////
CLERK STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The Clerk module used by the Master and its Safes.
TurboClerk public clerk;
/// @notice Emitted when the Clerk is updated.
/// @param user The user who triggered the update of the Clerk.
/// @param newClerk The new Clerk contract used by the Master.
event ClerkUpdated(address indexed user, TurboClerk newClerk);
/// @notice Update the Clerk used by the Master.
/// @param newClerk The new Clerk contract to be used by the Master.
function setClerk(TurboClerk newClerk) external requiresAuth {
clerk = newClerk;
emit ClerkUpdated(msg.sender, newClerk);
}
/*///////////////////////////////////////////////////////////////
DEFAULT SAFE AUTHORITY CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice The default authority to be used by created Safes.
Authority public defaultSafeAuthority;
/// @notice Emitted when the default safe authority is updated.
/// @param user The user who triggered the update of the default safe authority.
/// @param newDefaultSafeAuthority The new default authority to be used by created Safes.
event DefaultSafeAuthorityUpdated(address indexed user, Authority newDefaultSafeAuthority);
/// @notice Set the default authority to be used by created Safes.
/// @param newDefaultSafeAuthority The new default safe authority.
function setDefaultSafeAuthority(Authority newDefaultSafeAuthority) external requiresAuth {
// Update the default safe authority.
defaultSafeAuthority = newDefaultSafeAuthority;
emit DefaultSafeAuthorityUpdated(msg.sender, newDefaultSafeAuthority);
}
/*///////////////////////////////////////////////////////////////
SAFE STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The total Fei currently boosting Vaults.
uint256 public totalBoosted;
/// @notice Maps Safe addresses to the id they are stored under in the Safes array.
mapping(TurboSafe => uint256) public getSafeId;
/// @notice Maps Vault addresses to the total amount of Fei they've being boosted with.
mapping(ERC4626 => uint256) public getTotalBoostedForVault;
/// @notice Maps collateral types to the total amount of Fei boosted by Safes using it as collateral.
mapping(ERC20 => uint256) public getTotalBoostedAgainstCollateral;
/// @notice An array of all Safes created by the Master.
/// @dev The first Safe is purposely invalid to prevent any Safes from having an id of 0.
TurboSafe[] public safes;
/// @notice Returns all Safes created by the Master.
/// @return An array of all Safes created by the Master.
/// @dev This is provided because Solidity converts public arrays into index getters,
/// but we need a way to allow external contracts and users to access the whole array.
function getAllSafes() external view returns (TurboSafe[] memory) {
return safes;
}
/*///////////////////////////////////////////////////////////////
SAFE CREATION LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a new Safe is created.
/// @param user The user who created the Safe.
/// @param asset The asset of the Safe.
/// @param safe The newly deployed Safe contract.
/// @param id The index of the Safe in the safes array.
event TurboSafeCreated(address indexed user, ERC20 indexed asset, TurboSafe safe, uint256 id);
/// @notice Creates a new Turbo Safe which supports a specific asset.
/// @param asset The ERC20 token that the Safe should accept.
/// @return safe The newly deployed Turbo Safe which accepts the provided asset.
function createSafe(ERC20 asset) external requiresAuth returns (TurboSafe safe, uint256 id) {
// Create a new Safe using the default authority and provided asset.
safe = new TurboSafe(msg.sender, defaultSafeAuthority, asset);
// Add the safe to the list of Safes.
safes.push(safe);
unchecked {
// Get the index/id of the new Safe.
// Cannot underflow, we just pushed to it.
id = safes.length - 1;
}
// Store the id/index of the new Safe.
getSafeId[safe] = id;
emit TurboSafeCreated(msg.sender, asset, safe, id);
// Prepare a users array to whitelist the Safe.
address[] memory users = new address[](1);
users[0] = address(safe);
// Prepare an enabled array to whitelist the Safe.
bool[] memory enabled = new bool[](1);
enabled[0] = true;
// Whitelist the Safe to access the Turbo Fuse Pool.
FuseAdmin(pool.admin())._setWhitelistStatuses(users, enabled);
}
/*///////////////////////////////////////////////////////////////
SAFE CALLBACK LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Callback triggered whenever a Safe boosts a Vault.
/// @param asset The asset of the Safe.
/// @param vault The Vault that was boosted.
/// @param feiAmount The amount of Fei used to boost the Vault.
function onSafeBoost(
ERC20 asset,
ERC4626 vault,
uint256 feiAmount
) external {
// Get the caller as a Safe instance.
TurboSafe safe = TurboSafe(msg.sender);
// Ensure the Safe was created by this Master.
require(getSafeId[safe] != 0, "INVALID_SAFE");
// Update the total amount of Fei being using to boost Vaults.
totalBoosted += feiAmount;
// Cache the new total boosted for the Vault.
uint256 newTotalBoostedForVault;
// Cache the new total boosted against the Vault's collateral.
uint256 newTotalBoostedAgainstCollateral;
// Update the total amount of Fei being using to boost the Vault.
getTotalBoostedForVault[vault] = (newTotalBoostedForVault = getTotalBoostedForVault[vault] + feiAmount);
// Update the total amount of Fei boosted against the collateral type.
getTotalBoostedAgainstCollateral[asset] = (newTotalBoostedAgainstCollateral =
getTotalBoostedAgainstCollateral[asset] +
feiAmount);
// Check with the booster that the Safe is allowed to boost the Vault using this amount of Fei.
require(
booster.canSafeBoostVault(
safe,
asset,
vault,
feiAmount,
newTotalBoostedForVault,
newTotalBoostedAgainstCollateral
),
"BOOSTER_REJECTED"
);
}
/// @notice Callback triggered whenever a Safe withdraws from a Vault.
/// @param asset The asset of the Safe.
/// @param vault The Vault that was withdrawn from.
/// @param feiAmount The amount of Fei withdrawn from the Vault.
function onSafeLess(
ERC20 asset,
ERC4626 vault,
uint256 feiAmount
) external {
// Get the caller as a Safe instance.
TurboSafe safe = TurboSafe(msg.sender);
// Ensure the Safe was created by this Master.
require(getSafeId[safe] != 0, "INVALID_SAFE");
// Update the total amount of Fei being using to boost the Vault.
getTotalBoostedForVault[vault] -= feiAmount;
// Update the total amount of Fei being using to boost Vaults.
totalBoosted -= feiAmount;
// Update the total amount of Fei boosted against the collateral type.
getTotalBoostedAgainstCollateral[asset] -= feiAmount;
}
/*///////////////////////////////////////////////////////////////
SWEEP LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted a token is sweeped from the Master.
/// @param user The user who sweeped the token from the Master.
/// @param to The recipient of the sweeped tokens.
/// @param amount The amount of the token that was sweeped.
event TokenSweeped(address indexed user, address indexed to, ERC20 indexed token, uint256 amount);
/// @notice Claim tokens sitting idly in the Master.
/// @param to The recipient of the sweeped tokens.
/// @param token The token to sweep and send.
/// @param amount The amount of the token to sweep.
function sweep(
address to,
ERC20 token,
uint256 amount
) external requiresAuth {
emit TokenSweeped(msg.sender, to, token, amount);
// Transfer the sweeped tokens to the recipient.
token.safeTransfer(to, amount);
}
}
/// @title Turbo Safe
/// @author Transmissions11
/// @notice Fuse liquidity accelerator.
contract TurboSafe is Auth, ERC4626, ReentrancyGuard {
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The Master contract that created the Safe.
/// @dev Fees are paid directly to the Master, where they can be swept.
TurboMaster public immutable master;
/// @notice The Fei token on the network.
ERC20 public immutable fei;
/// @notice The Turbo Fuse Pool contract that collateral is held in and Fei is borrowed from.
Comptroller public immutable pool;
/// @notice The Fei cToken in the Turbo Fuse Pool that Fei is borrowed from.
CERC20 public immutable feiTurboCToken;
/// @notice The cToken that accepts the asset in the Turbo Fuse Pool.
CERC20 public immutable assetTurboCToken;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Safe that accepts a specific asset.
/// @param _owner The owner of the Safe.
/// @param _authority The Authority of the Safe.
/// @param _asset The ERC20 compliant token the Safe should accept.
constructor(
address _owner,
Authority _authority,
ERC20 _asset
)
Auth(_owner, _authority)
ERC4626(
_asset,
// ex: Dai Stablecoin Turbo Safe
string(abi.encodePacked(_asset.name(), " Turbo Safe")),
// ex: tsDAI
string(abi.encodePacked("ts", _asset.symbol()))
)
{
master = TurboMaster(msg.sender);
fei = master.fei();
// An asset of Fei makes no sense.
require(asset != fei, "INVALID_ASSET");
pool = master.pool();
feiTurboCToken = pool.cTokensByUnderlying(fei);
assetTurboCToken = pool.cTokensByUnderlying(asset);
// If the provided asset is not supported by the Turbo Fuse Pool, revert.
require(address(assetTurboCToken) != address(0), "UNSUPPORTED_ASSET");
// Construct an array of market(s) to enable as collateral.
CERC20[] memory marketsToEnter = new CERC20[](1);
marketsToEnter[0] = assetTurboCToken;
// Enter the market(s) and ensure to properly revert if there is an error.
require(pool.enterMarkets(marketsToEnter)[0] == 0, "ENTER_MARKETS_FAILED");
// Preemptively approve the asset to the Turbo Fuse Pool's corresponding cToken.
asset.safeApprove(address(assetTurboCToken), type(uint256).max);
// Preemptively approve Fei to the Turbo Fuse Pool's Fei cToken.
fei.safeApprove(address(feiTurboCToken), type(uint256).max);
}
/*///////////////////////////////////////////////////////////////
SAFE STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The current total amount of Fei the Safe is using to boost Vaults.
uint256 public totalFeiBoosted;
/// @notice Maps Vaults to the total amount of Fei they've being boosted with.
/// @dev Used to determine the fees to be paid back to the Master.
mapping(ERC4626 => uint256) public getTotalFeiBoostedForVault;
/*///////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/// @dev Checks the caller is authorized using either the Master's Authority or the Safe's local Authority.
modifier requiresLocalOrMasterAuth() {
// Check if the caller is the owner first:
if (msg.sender != owner) {
Authority masterAuth = master.authority(); // Avoid wasting gas calling the Master twice.
// If the Master's Authority does not exist or does not accept upfront:
if (address(masterAuth) == address(0) || !masterAuth.canCall(msg.sender, address(this), msg.sig)) {
Authority auth = authority; // Memoizing saves us a warm SLOAD, around 100 gas.
// The only authorization option left is via the local Authority, otherwise revert.
require(
address(auth) != address(0) && auth.canCall(msg.sender, address(this), msg.sig),
"UNAUTHORIZED"
);
}
}
_;
}
/// @dev Checks the caller is authorized using the Master's Authority.
modifier requiresMasterAuth() {
Authority masterAuth = master.authority(); // Avoid wasting gas calling the Master twice.
// Revert if the Master's Authority does not approve of the call and the caller is not the Master's owner.
require(
(address(masterAuth) != address(0) && masterAuth.canCall(msg.sender, address(this), msg.sig)) ||
msg.sender == master.owner(),
"UNAUTHORIZED"
);
_;
}
/*///////////////////////////////////////////////////////////////
ERC4626 LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Called after any type of deposit occurs.
/// @param assetAmount The amount of assets being deposited.
/// @dev Using requiresAuth here prevents unauthorized users from depositing.
function afterDeposit(uint256 assetAmount, uint256) internal override nonReentrant requiresAuth {
// Collateralize the assets in the Turbo Fuse Pool.
require(assetTurboCToken.mint(assetAmount) == 0, "MINT_FAILED");
}
/// @notice Called before any type of withdrawal occurs.
/// @param assetAmount The amount of assets being withdrawn.
/// @dev Using requiresAuth here prevents unauthorized users from withdrawing.
function beforeWithdraw(uint256 assetAmount, uint256) internal override nonReentrant requiresAuth {
// Withdraw the assets from the Turbo Fuse Pool.
require(assetTurboCToken.redeemUnderlying(assetAmount) == 0, "REDEEM_FAILED");
}
/// @notice Returns the total amount of assets held in the Safe.
/// @return The total amount of assets held in the Safe.
function totalAssets() public view override returns (uint256) {
return assetTurboCToken.balanceOf(address(this)).mulWadDown(assetTurboCToken.exchangeRateStored());
}
/*///////////////////////////////////////////////////////////////
BOOST/LESS LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a Vault is boosted by the Safe.
/// @param user The user who boosted the Vault.
/// @param vault The Vault that was boosted.
/// @param feiAmount The amount of Fei that was boosted to the Vault.
event VaultBoosted(address indexed user, ERC4626 indexed vault, uint256 feiAmount);
/// @notice Borrow Fei from the Turbo Fuse Pool and deposit it into an authorized Vault.
/// @param vault The Vault to deposit the borrowed Fei into.
/// @param feiAmount The amount of Fei to borrow and supply into the Vault.
function boost(ERC4626 vault, uint256 feiAmount) external nonReentrant requiresAuth {
// Ensure the Vault accepts Fei asset.
require(vault.asset() == fei, "NOT_FEI");
// Call the Master where it will do extra validation
// and update it's total count of funds used for boosting.
master.onSafeBoost(asset, vault, feiAmount);
// Increase the boost total proportionately.
totalFeiBoosted += feiAmount;
// Update the total Fei deposited into the Vault proportionately.
getTotalFeiBoostedForVault[vault] += feiAmount;
emit VaultBoosted(msg.sender, vault, feiAmount);
// Borrow the Fei amount from the Fei cToken in the Turbo Fuse Pool.
require(feiTurboCToken.borrow(feiAmount) == 0, "BORROW_FAILED");
// Approve the borrowed Fei to the specified Vault.
fei.safeApprove(address(vault), feiAmount);
// Deposit the Fei into the specified Vault.
vault.deposit(feiAmount, address(this));
}
/// @notice Emitted when a Vault is withdrawn from by the Safe.
/// @param user The user who lessed the Vault.
/// @param vault The Vault that was withdrawn from.
/// @param feiAmount The amount of Fei that was withdrawn from the Vault.
event VaultLessened(address indexed user, ERC4626 indexed vault, uint256 feiAmount);
/// @notice Withdraw Fei from a deposited Vault and use it to repay debt in the Turbo Fuse Pool.
/// @param vault The Vault to withdraw the Fei from.
/// @param feiAmount The amount of Fei to withdraw from the Vault and repay in the Turbo Fuse Pool.
function less(ERC4626 vault, uint256 feiAmount) external nonReentrant requiresLocalOrMasterAuth {
// Update the total Fei deposited into the Vault proportionately.
getTotalFeiBoostedForVault[vault] -= feiAmount;
// Decrease the boost total proportionately.
totalFeiBoosted -= feiAmount;
emit VaultLessened(msg.sender, vault, feiAmount);
// Withdraw the specified amount of Fei from the Vault.
vault.withdraw(feiAmount, address(this), address(this));
// Get out current amount of Fei debt in the Turbo Fuse Pool.
uint256 feiDebt = feiTurboCToken.borrowBalanceCurrent(address(this));
// Call the Master to allow it to update its accounting.
master.onSafeLess(asset, vault, feiAmount);
// If our debt balance decreased, repay the minimum.
// The surplus Fei will accrue as fees and can be sweeped.
if (feiAmount > feiDebt) feiAmount = feiDebt;
// Repay Fei debt in the Turbo Fuse Pool, unless we would repay nothing.
if (feiAmount != 0) require(feiTurboCToken.repayBorrow(feiAmount) == 0, "REPAY_FAILED");
}
/*///////////////////////////////////////////////////////////////
SLURP LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a Vault is slurped from by the Safe.
/// @param user The user who slurped the Vault.
/// @param vault The Vault that was slurped.
/// @param protocolFeeAmount The amount of Fei accrued as fees to the Master.
/// @param safeInterestAmount The amount of Fei accrued as interest to the Safe.
event VaultSlurped(
address indexed user,
ERC4626 indexed vault,
uint256 protocolFeeAmount,
uint256 safeInterestAmount
);
/// @notice Accrue any interest earned by the Safe in the Vault.
/// @param vault The Vault to accrue interest from, if any.
/// @dev Sends a portion of the interest to the Master, as determined by the Clerk.
function slurp(ERC4626 vault) external nonReentrant requiresLocalOrMasterAuth returns(uint256 safeInterestAmount) {
// Cache the total Fei currently boosting the Vault.
uint256 totalFeiBoostedForVault = getTotalFeiBoostedForVault[vault];
// Ensure the Safe has Fei currently boosting the Vault.
require(totalFeiBoostedForVault != 0, "NO_FEI_BOOSTED");
// Compute the amount of Fei interest the Safe generated by boosting the Vault.
uint256 interestEarned = vault.previewRedeem(vault.balanceOf(address(this))) - totalFeiBoostedForVault;
// Compute what percentage of the interest earned will go back to the Safe.
uint256 protocolFeePercent = master.clerk().getFeePercentageForSafe(this, asset);
// Compute the amount of Fei the protocol will retain as fees.
uint256 protocolFeeAmount = interestEarned.mulWadDown(protocolFeePercent);
// Compute the amount of Fei the Safe will retain as interest.
safeInterestAmount = interestEarned - protocolFeeAmount;
emit VaultSlurped(msg.sender, vault, protocolFeeAmount, safeInterestAmount);
vault.withdraw(interestEarned, address(this), address(this));
// If we have unaccrued fees, withdraw them from the Vault and transfer them to the Master.
if (protocolFeeAmount != 0) fei.transfer(address(master), protocolFeeAmount);
}
/*///////////////////////////////////////////////////////////////
SWEEP LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted a token is sweeped from the Safe.
/// @param user The user who sweeped the token from the Safe.
/// @param to The recipient of the sweeped tokens.
/// @param amount The amount of the token that was sweeped.
event TokenSweeped(address indexed user, address indexed to, ERC20 indexed token, uint256 amount);
/// @notice Claim tokens sitting idly in the Safe.
/// @param to The recipient of the sweeped tokens.
/// @param token The token to sweep and send.
/// @param amount The amount of the token to sweep.
function sweep(
address to,
ERC20 token,
uint256 amount
) external requiresAuth {
// Ensure the caller is not trying to steal Vault shares or collateral cTokens.
require(getTotalFeiBoostedForVault[ERC4626(address(token))] == 0 && token != assetTurboCToken, "INVALID_TOKEN");
emit TokenSweeped(msg.sender, to, token, amount);
// Transfer the sweeped tokens to the recipient.
token.safeTransfer(to, amount);
}
/*///////////////////////////////////////////////////////////////
GIB LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a Safe is gibbed.
/// @param user The user who gibbed the Safe.
/// @param to The recipient of the impounded collateral.
/// @param assetAmount The amount of underling tokens impounded.
event SafeGibbed(address indexed user, address indexed to, uint256 assetAmount);
/// @notice Impound a specific amount of a Safe's collateral.
/// @param to The address to send the impounded collateral to.
/// @param assetAmount The amount of the asset to impound.
/// @dev Debt must be repaid in advance, or the redemption will fail.
function gib(address to, uint256 assetAmount) external nonReentrant requiresMasterAuth {
emit SafeGibbed(msg.sender, to, assetAmount);
// Withdraw the specified amount of assets from the Turbo Fuse Pool.
require(assetTurboCToken.redeemUnderlying(assetAmount) == 0, "REDEEM_FAILED");
// Transfer the assets to the authorized caller.
asset.safeTransfer(to, assetAmount);
}
}
/// @title Turbo Booster
/// @author Transmissions11
/// @notice Boost authorization module.
contract TurboBooster is Auth, ENSReverseRecordAuth {
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Booster contract.
/// @param _owner The owner of the Booster.
/// @param _authority The Authority of the Booster.
constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
/*///////////////////////////////////////////////////////////////
GLOBAL FREEZE CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice Whether boosting is currently frozen.
bool public frozen;
/// @notice Emitted when boosting is frozen or unfrozen.
/// @param user The user who froze or unfroze boosting.
/// @param frozen Whether boosting is now frozen.
event FreezeStatusUpdated(address indexed user, bool frozen);
/// @notice Sets whether boosting is frozen.
/// @param freeze Whether boosting will be frozen.
function setFreezeStatus(bool freeze) external requiresAuth {
// Update freeze status.
frozen = freeze;
emit FreezeStatusUpdated(msg.sender, freeze);
}
/*///////////////////////////////////////////////////////////////
VAULT BOOST CAP CONFIGURATION
//////////////////////////////////////////////////////////////*/
ERC4626[] public boostableVaults;
/// @notice exposes an array of boostable vaults. Only used for visibility.
function getBoostableVaults() external view returns(ERC4626[] memory) {
return boostableVaults;
}
/// @notice Maps Vaults to the cap on the amount of Fei used to boost them.
mapping(ERC4626 => uint256) public getBoostCapForVault;
/// @notice Emitted when a Vault's boost cap is updated.
/// @param vault The Vault who's boost cap was updated.
/// @param newBoostCap The new boost cap for the Vault.
event BoostCapUpdatedForVault(address indexed user, ERC4626 indexed vault, uint256 newBoostCap);
/// @notice Sets a Vault's boost cap.
/// @param vault The Vault to set the boost cap for.
/// @param newBoostCap The new boost cap for the Vault.
function setBoostCapForVault(ERC4626 vault, uint256 newBoostCap) external requiresAuth {
require(newBoostCap != 0, "cap is zero");
// Add to boostable vaults array
if (getBoostCapForVault[vault] == 0) {
boostableVaults.push(vault);
}
// Update the boost cap for the Vault.
getBoostCapForVault[vault] = newBoostCap;
emit BoostCapUpdatedForVault(msg.sender, vault, newBoostCap);
}
/*///////////////////////////////////////////////////////////////
COLLATERAL BOOST CAP CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice Maps collateral types to the cap on the amount of Fei boosted against them.
mapping(ERC20 => uint256) public getBoostCapForCollateral;
/// @notice Emitted when a collateral type's boost cap is updated.
/// @param collateral The collateral type who's boost cap was updated.
/// @param newBoostCap The new boost cap for the collateral type.
event BoostCapUpdatedForCollateral(address indexed user, ERC20 indexed collateral, uint256 newBoostCap);
/// @notice Sets a collateral type's boost cap.
/// @param collateral The collateral type to set the boost cap for.
/// @param newBoostCap The new boost cap for the collateral type.
function setBoostCapForCollateral(ERC20 collateral, uint256 newBoostCap) external requiresAuth {
// Update the boost cap for the collateral type.
getBoostCapForCollateral[collateral] = newBoostCap;
emit BoostCapUpdatedForCollateral(msg.sender, collateral, newBoostCap);
}
/*///////////////////////////////////////////////////////////////
AUTHORIZATION LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Returns whether a Safe is authorized to boost a Vault.
/// @param safe The Safe to check is authorized to boost the Vault.
/// @param collateral The collateral/asset of the Safe.
/// @param vault The Vault to check the Safe is authorized to boost.
/// @param feiAmount The amount of Fei asset to check the Safe is authorized boost the Vault with.
/// @param newTotalBoostedForVault The total amount of Fei that will boosted to the Vault after boost (if it is not rejected).
/// @param newTotalBoostedAgainstCollateral The total amount of Fei that will be boosted against the Safe's collateral type after this boost.
/// @return Whether the Safe is authorized to boost the Vault with the given amount of Fei asset.
function canSafeBoostVault(
TurboSafe safe,
ERC20 collateral,
ERC4626 vault,
uint256 feiAmount,
uint256 newTotalBoostedForVault,
uint256 newTotalBoostedAgainstCollateral
) external view returns (bool) {
return
!frozen &&
getBoostCapForVault[vault] >= newTotalBoostedForVault &&
getBoostCapForCollateral[collateral] >= newTotalBoostedAgainstCollateral;
}
}
/**
@title Turbo Admin of Turbo Fuse Pool and Turbo Timelock
*/
contract TurboAdmin is Auth, ENSReverseRecordAuth {
/// @notice generic error thrown when comptroller call fails
error ComptrollerError();
/// @notice the fuse comptroller associated with the TurboAdmin
Comptroller public immutable comptroller;
/// @notice the turbo timelock
TimelockController public immutable timelock;
/// @notice constant zero interest rate model
address public constant ZERO_IRM = 0xC9dB5A1034BcBcca3f59dD61dbeE31b78CeFD126;
/// @notice cToken implementation
address public constant CTOKEN_IMPL = 0x67Db14E73C2Dce786B5bbBfa4D010dEab4BBFCF9;
/// @param _comptroller the fuse comptroller
constructor(Comptroller _comptroller, TimelockController _timelock, Authority _authority) Auth(address(0), _authority) {
comptroller = _comptroller;
timelock = _timelock;
}
// ************ TURBO ADMIN FUNCTIONS ************
function addCollateral(
address underlying,
string calldata name,
string calldata symbol,
uint256 collateralFactorMantissa,
uint256 supplyCap
) external requiresAuth {
bytes memory constructorData = abi.encode(
underlying,
address(comptroller),
ZERO_IRM,
name,
symbol,
CTOKEN_IMPL,
new bytes(0),
0, // zero admin fee
0 // zero reserve factor
);
if (
comptroller._deployMarket(
false,
constructorData,
collateralFactorMantissa
) != 0
) revert ComptrollerError();
// set borrow paused
CERC20 cToken = comptroller.cTokensByUnderlying(ERC20(underlying));
_setBorrowPausedInternal(cToken, true);
CERC20[] memory markets = new CERC20[](1);
markets[0] = cToken;
uint256[] memory caps = new uint256[](1);
caps[0] = supplyCap;
comptroller._setMarketSupplyCaps(markets, caps);
}
// ************ BORROW GUARDIAN FUNCTIONS ************
/**
* @notice Set the given supply caps for the given cToken markets. Supplying that brings total underlying supply to or above supply cap will revert.
* @dev Admin or borrowCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying.
* @param cTokens The addresses of the markets (tokens) to change the supply caps for
* @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.
*/
function _setMarketSupplyCaps(
CERC20[] memory cTokens,
uint256[] calldata newSupplyCaps
) external requiresAuth {
_setMarketSupplyCapsInternal(cTokens, newSupplyCaps);
}
function _setMarketSupplyCapsByUnderlying(
address[] calldata underlyings,
uint256[] calldata newSupplyCaps
) external requiresAuth {
_setMarketSupplyCapsInternal(
_underlyingToCTokens(underlyings),
newSupplyCaps
);
}
function _setMarketSupplyCapsInternal(
CERC20[] memory cTokens,
uint256[] calldata newSupplyCaps
) internal {
comptroller._setMarketSupplyCaps(cTokens, newSupplyCaps);
}
function _underlyingToCTokens(address[] calldata underlyings)
internal
view
returns (CERC20[] memory)
{
CERC20[] memory cTokens = new CERC20[](underlyings.length);
for (uint256 i = 0; i < underlyings.length; i++) {
CERC20 cToken = comptroller.cTokensByUnderlying(ERC20(underlyings[i]));
require(address(cToken) != address(0), "cToken doesn't exist");
cTokens[i] = CERC20(cToken);
}
return cTokens;
}
/**
* @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param cTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(
CERC20[] memory cTokens,
uint256[] calldata newBorrowCaps
) external requiresAuth {
_setMarketBorrowCapsInternal(cTokens, newBorrowCaps);
}
function _setMarketBorrowCapsInternal(
CERC20[] memory cTokens,
uint256[] calldata newBorrowCaps
) internal {
comptroller._setMarketBorrowCaps(cTokens, newBorrowCaps);
}
function _setMarketBorrowCapsByUnderlying(
address[] calldata underlyings,
uint256[] calldata newBorrowCaps
) external requiresAuth {
_setMarketBorrowCapsInternal(
_underlyingToCTokens(underlyings),
newBorrowCaps
);
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian)
external
requiresAuth
{
comptroller._setBorrowCapGuardian(newBorrowCapGuardian);
}
// ************ PAUSE GUARDIAN FUNCTIONS ************
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian)
external
requiresAuth
returns (uint256)
{
return comptroller._setPauseGuardian(newPauseGuardian);
}
function _setMintPausedByUnderlying(ERC20 underlying, bool state)
external
requiresAuth
returns (bool)
{
CERC20 cToken = comptroller.cTokensByUnderlying(underlying);
require(address(cToken) != address(0), "cToken doesn't exist");
return _setMintPausedInternal(cToken, state);
}
function _setMintPaused(CERC20 cToken, bool state)
external
requiresAuth
returns (bool)
{
return _setMintPausedInternal(cToken, state);
}
function _setMintPausedInternal(CERC20 cToken, bool state)
internal
returns (bool)
{
return comptroller._setMintPaused(cToken, state);
}
function _setBorrowPausedByUnderlying(ERC20 underlying, bool state)
external
requiresAuth
returns (bool)
{
CERC20 cToken = comptroller.cTokensByUnderlying(underlying);
require(address(cToken) != address(0), "cToken doesn't exist");
return _setBorrowPausedInternal(cToken, state);
}
function _setBorrowPausedInternal(CERC20 cToken, bool state)
internal
returns (bool)
{
return comptroller._setBorrowPaused(cToken, state);
}
function _setBorrowPaused(CERC20 cToken, bool state)
external
requiresAuth
returns (bool)
{
return _setBorrowPausedInternal(CERC20(cToken), state);
}
function _setTransferPaused(bool state)
external
requiresAuth
returns (bool)
{
return comptroller._setTransferPaused(state);
}
function _setSeizePaused(bool state)
external
requiresAuth
returns (bool)
{
return comptroller._setSeizePaused(state);
}
// ************ FUSE ADMIN FUNCTIONS ************
function oracleAdd(
address[] calldata underlyings,
address[] calldata _oracles
) external requiresAuth {
comptroller.oracle().add(underlyings, _oracles);
}
function oracleChangeAdmin(address newAdmin) external requiresAuth {
comptroller.oracle().changeAdmin(newAdmin);
}
function _addRewardsDistributor(address distributor)
external
requiresAuth
{
if (comptroller._addRewardsDistributor(distributor) != 0)
revert ComptrollerError();
}
function _setWhitelistEnforcement(bool enforce)
external
requiresAuth
{
if (comptroller._setWhitelistEnforcement(enforce) != 0)
revert ComptrollerError();
}
function _setWhitelistStatuses(
address[] calldata suppliers,
bool[] calldata statuses
) external requiresAuth {
if (comptroller._setWhitelistStatuses(suppliers, statuses) != 0)
revert ComptrollerError();
}
function _setPriceOracle(address newOracle) public requiresAuth {
if (comptroller._setPriceOracle(newOracle) != 0)
revert ComptrollerError();
}
function _setCloseFactor(uint256 newCloseFactorMantissa)
external
requiresAuth
{
if (comptroller._setCloseFactor(newCloseFactorMantissa) != 0)
revert ComptrollerError();
}
function _setCollateralFactor(
CERC20 cToken,
uint256 newCollateralFactorMantissa
) public requiresAuth {
if (
comptroller._setCollateralFactor(
cToken,
newCollateralFactorMantissa
) != 0
) revert ComptrollerError();
}
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa)
external
requiresAuth
{
if (
comptroller._setLiquidationIncentive(
newLiquidationIncentiveMantissa
) != 0
) revert ComptrollerError();
}
function _deployMarket(
address underlying,
address irm,
string calldata name,
string calldata symbol,
address impl,
bytes calldata data,
uint256 reserveFactor,
uint256 adminFee,
uint256 collateralFactorMantissa
) external requiresAuth {
bytes memory constructorData = abi.encode(
underlying,
address(comptroller),
irm,
name,
symbol,
impl,
data,
reserveFactor,
adminFee
);
if (
comptroller._deployMarket(
false,
constructorData,
collateralFactorMantissa
) != 0
) revert ComptrollerError();
}
function _unsupportMarket(CERC20 cToken) external requiresAuth {
if (comptroller._unsupportMarket(cToken) != 0)
revert ComptrollerError();
}
function _toggleAutoImplementations(bool enabled)
public
requiresAuth
{
if (comptroller._toggleAutoImplementations(enabled) != 0)
revert ComptrollerError();
}
function scheduleSetPendingAdmin(address newPendingAdmin) public requiresAuth {
_schedule(address(this), abi.encodeWithSelector(this._setPendingAdmin.selector, newPendingAdmin));
}
function _setPendingAdmin(address newPendingAdmin)
public
{
require(msg.sender == address(timelock), "timelock");
if (comptroller._setPendingAdmin(newPendingAdmin) != 0)
revert ComptrollerError();
}
function _acceptAdmin() public {
if (comptroller._acceptAdmin() != 0) revert ComptrollerError();
}
// ************ TIMELOCK ADMIN FUNCTIONS ************
function schedule(address target, bytes memory data) public requiresAuth {
_schedule(target, data);
}
function _schedule(address target, bytes memory data) internal {
timelock.schedule(target, 0, data, bytes32(0), keccak256(abi.encodePacked(block.timestamp)), 15 days);
}
function cancel(bytes32 id) public requiresAuth {
timelock.cancel(id);
}
function execute(address target, bytes memory data, bytes32 salt) public requiresAuth {
timelock.execute(target, 0, data, bytes32(0), salt);
}
}
/// @title Fei
/// @author Fei Protocol
/// @notice Minimal interface for the Fei token.
abstract contract Fei is ERC20 {
function mint(address to, uint256 amount) external virtual;
}
/// @title Turbo Gibber
/// @author Transmissions11
/// @notice Atomic impounder module.
contract TurboGibber is Auth, ReentrancyGuard, ENSReverseRecordAuth {
using SafeTransferLib for Fei;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The Master contract.
/// @dev Used to validate Safes are legitimate.
TurboMaster public immutable master;
/// @notice The Fei token on the network.
Fei public immutable fei;
/// @notice The Fei cToken in the Turbo Fuse Pool.
CERC20 public immutable feiTurboCToken;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Gibber contract.
/// @param _master The Master of the Gibber.
/// @param _owner The owner of the Gibber.
/// @param _authority The Authority of the Gibber.
constructor(
TurboMaster _master,
address _owner,
Authority _authority
) Auth(_owner, _authority) {
master = _master;
fei = Fei(address(master.fei()));
feiTurboCToken = master.pool().cTokensByUnderlying(fei);
// Preemptively approve to the Fei cToken in the Turbo Fuse Pool.
fei.safeApprove(address(feiTurboCToken), type(uint256).max);
}
/*///////////////////////////////////////////////////////////////
ATOMIC IMPOUND LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted an impound is executed.
/// @param user The user who executed the impound.
/// @param safe The Safe that was impounded.
/// @param feiAmount The amount of Fei that was repaid.
/// @param assetAmount The amount of assets impounded.
event ImpoundExecuted(address indexed user, TurboSafe indexed safe, uint256 feiAmount, uint256 assetAmount);
/// @notice Impound a safe.
/// @param safe The Safe to be impounded.
/// @param feiAmount The amount of Fei to repay the Safe's debt with.
/// @param assetAmount The amount of assets to impound.
/// @param to The recipient of the impounded collateral tokens.
function impound(
TurboSafe safe,
uint256 feiAmount,
uint256 assetAmount,
address to
) external requiresAuth nonReentrant {
// Ensure the Safe is registered with the Master.
require(master.getSafeId(safe) != 0);
emit ImpoundExecuted(msg.sender, safe, feiAmount, assetAmount);
// Mint the Fei amount requested.
fei.mint(address(this), feiAmount);
// Repay the safe's Fei debt with the minted Fei, ensuring to catch cToken errors.
require(feiTurboCToken.repayBorrowBehalf(address(safe), feiAmount) == 0, "REPAY_FAILED");
// Impound some of the safe's collateral and send it to the chosen recipient.
safe.gib(to, assetAmount);
}
/// @notice Impound all of a safe's collateral.
/// @param safe The Safe to be impounded.
/// @param to The recipient of the impounded collateral tokens.
function impoundAll(TurboSafe safe, address to) external requiresAuth nonReentrant {
// Ensure the Safe is registered with the Master.
require(master.getSafeId(safe) != 0);
// Get the asset cToken in the Turbo Fuse Pool.
CERC20 assetTurboCToken = safe.assetTurboCToken();
// Get the amount of assets to impound from the Safe.
uint256 assetAmount = assetTurboCToken.balanceOfUnderlying(address(safe));
// Get the amount of Fei debt to repay for the Safe.
uint256 feiAmount = feiTurboCToken.borrowBalanceCurrent(address(safe));
emit ImpoundExecuted(msg.sender, safe, feiAmount, assetAmount);
// Mint the Fei amount requested.
fei.mint(address(this), feiAmount);
// Repay the safe's Fei debt with the minted Fei, ensuring to catch cToken errors.
require(feiTurboCToken.repayBorrowBehalf(address(safe), feiAmount) == 0, "REPAY_FAILED");
// Impound all of the safe's collateral and send it to the chosen recipient.
safe.gib(to, assetAmount);
}
}
/// @title Turbo Savior
/// @author Transmissions11
/// @notice Safe repayment module.
contract TurboSavior is Auth, ReentrancyGuard, ENSReverseRecordAuth {
using FixedPointMathLib for uint256;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The Master contract.
/// @dev Used to validate Safes are legitimate.
TurboMaster public immutable master;
/// @notice The Fei token on the network.
Fei public immutable fei;
/// @notice The Turbo Fuse Pool used by the Master.
Comptroller public immutable pool;
/// @notice The Fei cToken in the Turbo Fuse Pool.
CERC20 public immutable feiTurboCToken;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Creates a new Turbo Savior contract.
/// @param _master The Master of the Savior.
/// @param _owner The owner of the Savior.
/// @param _authority The Authority of the Savior.
constructor(
TurboMaster _master,
address _owner,
Authority _authority
) Auth(_owner, _authority) {
master = _master;
fei = Fei(address(master.fei()));
pool = master.pool();
feiTurboCToken = pool.cTokensByUnderlying(fei);
}
/*///////////////////////////////////////////////////////////////
LINE LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice The minimum percentage debt must make up of the borrow limit for a Safe to be saved.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public minDebtPercentageForSaving;
/// @notice Emitted when the minimum debt percentage for saving is updated.
/// @param newDefaultFeePercentage The new minimum debt percentage for saving.
event MinDebtPercentageForSavingUpdated(address indexed user, uint256 newDefaultFeePercentage);
/// @notice Sets the minimum debt percentage.
/// @param newMinDebtPercentageForSaving The new minimum debt percentage.
function setMinDebtPercentageForSaving(uint256 newMinDebtPercentageForSaving) external requiresAuth {
// A minimum debt percentage over 100% makes no sense.
require(newMinDebtPercentageForSaving <= 1e18, "PERCENT_TOO_HIGH");
// Update the minimum debt percentage.
minDebtPercentageForSaving = newMinDebtPercentageForSaving;
emit MinDebtPercentageForSavingUpdated(msg.sender, newMinDebtPercentageForSaving);
}
/*///////////////////////////////////////////////////////////////
SAVE LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted a save is executed.
/// @param user The user who executed the save.
/// @param safe The Safe that was saved.
/// @param vault The Vault that was lessed.
/// @param feiAmount The amount of Fei that was lessed.
event SafeSaved(address indexed user, TurboSafe indexed safe, ERC4626 indexed vault, uint256 feiAmount);
/// @notice Save a Safe (call less on owner's behalf to prevent liquidation).
/// @param safe The Safe to be saved.
/// @param vault The Vault to less from.
/// @param feiAmount The amount of Fei to less from the Safe.
function save(
TurboSafe safe,
ERC4626 vault,
uint256 feiAmount
) external requiresAuth nonReentrant {
// Ensure the Safe is registered with the Master.
require(master.getSafeId(safe) != 0);
emit SafeSaved(msg.sender, safe, vault, feiAmount);
// Cache the Safe's collateral asset.
CERC20 assetTurboCToken = safe.assetTurboCToken();
// Cache the pool's current oracle.
PriceFeed oracle = pool.oracle();
// Get the Safe's asset's collateral factor in the Turbo Fuse Pool.
(, uint256 collateralFactor) = pool.markets(assetTurboCToken);
// Compute the value of the Safe's collateral. Rounded down to favor saving.
uint256 borrowLimit = assetTurboCToken
.balanceOf(address(safe))
.mulWadDown(assetTurboCToken.exchangeRateStored())
.mulWadDown(collateralFactor)
.mulWadDown(oracle.getUnderlyingPrice(assetTurboCToken));
// Compute the value of the Safe's debt. Rounding up to favor saving them.
uint256 debtValue = feiTurboCToken.borrowBalanceCurrent(address(safe)).mulWadUp(
oracle.getUnderlyingPrice(feiTurboCToken)
);
// Ensure the Safe's debt percentage is high enough to justify saving, otherwise revert.
require(
borrowLimit != 0 && debtValue.divWadUp(borrowLimit) >= minDebtPercentageForSaving,
"DEBT_PERCENT_TOO_LOW"
);
// Less the Fei from the Safe.
safe.less(vault, feiAmount);
}
}
/// @title ERC4626 interface
/// @author Fei Protocol
/// See: https://eips.ethereum.org/EIPS/eip-4626
abstract contract IERC4626 is ERC20 {
/*////////////////////////////////////////////////////////
Events
////////////////////////////////////////////////////////*/
/// @notice `sender` has exchanged `assets` for `shares`,
/// and transferred those `shares` to `receiver`.
event Deposit(
address indexed sender,
address indexed receiver,
uint256 assets,
uint256 shares
);
/// @notice `sender` has exchanged `shares` for `assets`,
/// and transferred those `assets` to `receiver`.
event Withdraw(
address indexed sender,
address indexed receiver,
uint256 assets,
uint256 shares
);
/*////////////////////////////////////////////////////////
Vault properties
////////////////////////////////////////////////////////*/
/// @notice The address of the underlying ERC20 token used for
/// the Vault for accounting, depositing, and withdrawing.
function asset() external view virtual returns(address asset);
/// @notice Total amount of the underlying asset that
/// is "managed" by Vault.
function totalAssets() external view virtual returns(uint256 totalAssets);
/*////////////////////////////////////////////////////////
Deposit/Withdrawal Logic
////////////////////////////////////////////////////////*/
/// @notice Mints `shares` Vault shares to `receiver` by
/// depositing exactly `assets` of underlying tokens.
function deposit(uint256 assets, address receiver) external virtual returns(uint256 shares);
/// @notice Mints exactly `shares` Vault shares to `receiver`
/// by depositing `assets` of underlying tokens.
function mint(uint256 shares, address receiver) external virtual returns(uint256 assets);
/// @notice Redeems `shares` from `owner` and sends `assets`
/// of underlying tokens to `receiver`.
function withdraw(uint256 assets, address receiver, address owner) external virtual returns(uint256 shares);
/// @notice Redeems `shares` from `owner` and sends `assets`
/// of underlying tokens to `receiver`.
function redeem(uint256 shares, address receiver, address owner) external virtual returns(uint256 assets);
/*////////////////////////////////////////////////////////
Vault Accounting Logic
////////////////////////////////////////////////////////*/
/// @notice The amount of shares that the vault would
/// exchange for the amount of assets provided, in an
/// ideal scenario where all the conditions are met.
function convertToShares(uint256 assets) external view virtual returns(uint256 shares);
/// @notice The amount of assets that the vault would
/// exchange for the amount of shares provided, in an
/// ideal scenario where all the conditions are met.
function convertToAssets(uint256 shares) external view virtual returns(uint256 assets);
/// @notice Total number of underlying assets that can
/// be deposited by `owner` into the Vault, where `owner`
/// corresponds to the input parameter `receiver` of a
/// `deposit` call.
function maxDeposit(address owner) external view virtual returns(uint256 maxAssets);
/// @notice Allows an on-chain or off-chain user to simulate
/// the effects of their deposit at the current block, given
/// current on-chain conditions.
function previewDeposit(uint256 assets) external view virtual returns(uint256 shares);
/// @notice Total number of underlying shares that can be minted
/// for `owner`, where `owner` corresponds to the input
/// parameter `receiver` of a `mint` call.
function maxMint(address owner) external view virtual returns(uint256 maxShares);
/// @notice Allows an on-chain or off-chain user to simulate
/// the effects of their mint at the current block, given
/// current on-chain conditions.
function previewMint(uint256 shares) external view virtual returns(uint256 assets);
/// @notice Total number of underlying assets that can be
/// withdrawn from the Vault by `owner`, where `owner`
/// corresponds to the input parameter of a `withdraw` call.
function maxWithdraw(address owner) external view virtual returns(uint256 maxAssets);
/// @notice Allows an on-chain or off-chain user to simulate
/// the effects of their withdrawal at the current block,
/// given current on-chain conditions.
function previewWithdraw(uint256 assets) external view virtual returns(uint256 shares);
/// @notice Total number of underlying shares that can be
/// redeemed from the Vault by `owner`, where `owner` corresponds
/// to the input parameter of a `redeem` call.
function maxRedeem(address owner) external view virtual returns(uint256 maxShares);
/// @notice Allows an on-chain or off-chain user to simulate
/// the effects of their redeemption at the current block,
/// given current on-chain conditions.
function previewRedeem(uint256 shares) external view virtual returns(uint256 assets);
}
/**
@title ERC4626Router Base Interface
@author joeysantoro
@notice A canonical router between ERC4626 Vaults https://eips.ethereum.org/EIPS/eip-4626
The base router is a multicall style router inspired by Uniswap v3 with built-in features for permit, WETH9 wrap/unwrap, and ERC20 token pulling/sweeping/approving.
It includes methods for the four mutable ERC4626 functions deposit/mint/withdraw/redeem as well.
These can all be arbitrarily composed using the multicall functionality of the router.
NOTE the router is capable of pulling any approved token from your wallet. This is only possible when your address is msg.sender, but regardless be careful when interacting with the router or ERC4626 Vaults.
The router makes no special considerations for unique ERC20 implementations such as fee on transfer.
There are no built in protections for unexpected behavior beyond enforcing the minSharesOut is received.
*/
interface IERC4626RouterBase {
/************************** Errors **************************/
/// @notice thrown when amount of assets received is below the min set by caller
error MinAmountError();
/// @notice thrown when amount of shares received is below the min set by caller
error MinSharesError();
/// @notice thrown when amount of assets received is above the max set by caller
error MaxAmountError();
/// @notice thrown when amount of shares received is above the max set by caller
error MaxSharesError();
/************************** Mint **************************/
/**
@notice mint `shares` from an ERC4626 vault.
@param vault The ERC4626 vault to mint shares from.
@param to The destination of ownership shares.
@param shares The amount of shares to mint from `vault`.
@param maxAmountIn The max amount of assets used to mint.
@return amountIn the amount of assets used to mint by `to`.
@dev throws MaxAmountError
*/
function mint(
IERC4626 vault,
address to,
uint256 shares,
uint256 maxAmountIn
) external payable returns (uint256 amountIn);
/************************** Deposit **************************/
/**
@notice deposit `amount` to an ERC4626 vault.
@param vault The ERC4626 vault to deposit assets to.
@param to The destination of ownership shares.
@param amount The amount of assets to deposit to `vault`.
@param minSharesOut The min amount of `vault` shares received by `to`.
@return sharesOut the amount of shares received by `to`.
@dev throws MinSharesError
*/
function deposit(
IERC4626 vault,
address to,
uint256 amount,
uint256 minSharesOut
) external payable returns (uint256 sharesOut);
/************************** Withdraw **************************/
/**
@notice withdraw `amount` from an ERC4626 vault.
@param vault The ERC4626 vault to withdraw assets from.
@param to The destination of assets.
@param amount The amount of assets to withdraw from vault.
@param minSharesOut The min amount of shares received by `to`.
@return sharesOut the amount of shares received by `to`.
@dev throws MaxSharesError
*/
function withdraw(
IERC4626 vault,
address to,
uint256 amount,
uint256 minSharesOut
) external payable returns (uint256 sharesOut);
/************************** Redeem **************************/
/**
@notice redeem `shares` shares from an ERC4626 vault.
@param vault The ERC4626 vault to redeem shares from.
@param to The destination of assets.
@param shares The amount of shares to redeem from vault.
@param minAmountOut The min amount of assets received by `to`.
@return amountOut the amount of assets received by `to`.
@dev throws MinAmountError
*/
function redeem(
IERC4626 vault,
address to,
uint256 shares,
uint256 minAmountOut
) external payable returns (uint256 amountOut);
}
// forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/ISelfPermit.sol
/// @title Self Permit
/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
interface ISelfPermit {
/// @notice Permits this contract to spend a given token from `msg.sender`
/// @dev The `owner` is always msg.sender and the `spender` is always address(this).
/// @param token The address of the token spent
/// @param value The amount that can be spent of token
/// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermit(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend a given token from `msg.sender`
/// @dev The `owner` is always msg.sender and the `spender` is always address(this).
/// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit
/// @param token The address of the token spent
/// @param value The amount that can be spent of token
/// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitIfNecessary(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
/// @dev The `owner` is always msg.sender and the `spender` is always address(this)
/// @param token The address of the token spent
/// @param nonce The current nonce of the owner
/// @param expiry The timestamp at which the permit is no longer valid
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
/// @dev The `owner` is always msg.sender and the `spender` is always address(this)
/// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.
/// @param token The address of the token spent
/// @param nonce The current nonce of the owner
/// @param expiry The timestamp at which the permit is no longer valid
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitAllowedIfNecessary(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/external/IERC20PermitAllowed.sol
/// @title Interface for permit
/// @notice Interface used by DAI/CHAI for permit
interface IERC20PermitAllowed {
/// @notice Approve the spender to spend some tokens via the holder signature
/// @dev This is the permit interface used by DAI and CHAI
/// @param holder The address of the token holder, the token owner
/// @param spender The address of the token spender
/// @param nonce The holder's nonce, increases at each call to permit
/// @param expiry The timestamp at which the permit is no longer valid
/// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
/// @title Self Permit
/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
/// @dev These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function
/// that requires an approval in a single transaction.
abstract contract SelfPermit is ISelfPermit {
/// @inheritdoc ISelfPermit
function selfPermit(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public payable override {
ERC20(token).permit(msg.sender, address(this), value, deadline, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitIfNecessary(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
if (ERC20(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public payable override {
IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitAllowedIfNecessary(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
if (ERC20(token).allowance(msg.sender, address(this)) < type(uint256).max)
selfPermitAllowed(token, nonce, expiry, v, r, s);
}
}// forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/Multicall.sol
// forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/IMulticall.sol
/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) public payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}/**
@title Periphery Payments
@notice Immutable state used by periphery contracts
Largely Forked from https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/PeripheryPayments.sol
Changes:
* no interface
* no inheritdoc
* add immutable WETH9 in constructor instead of PeripheryImmutableState
* receive from any address
* Solmate interfaces and transfer lib
* casting
* add approve, wrapWETH9 and pullToken
*/
abstract contract PeripheryPayments {
using SafeTransferLib for *;
IWETH9 public immutable WETH9;
constructor(IWETH9 _WETH9) {
WETH9 = _WETH9;
}
receive() external payable {}
function approve(ERC20 token, address to, uint256 amount) public payable {
token.safeApprove(to, amount);
}
function unwrapWETH9(uint256 amountMinimum, address recipient) public payable {
uint256 balanceWETH9 = WETH9.balanceOf(address(this));
require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9');
if (balanceWETH9 > 0) {
WETH9.withdraw(balanceWETH9);
recipient.safeTransferETH(balanceWETH9);
}
}
function wrapWETH9() public payable {
if (address(this).balance > 0) WETH9.deposit{value: address(this).balance}(); // wrap everything
}
function pullToken(ERC20 token, uint256 amount, address recipient) public payable {
token.safeTransferFrom(msg.sender, recipient, amount);
}
function sweepToken(
ERC20 token,
uint256 amountMinimum,
address recipient
) public payable {
uint256 balanceToken = token.balanceOf(address(this));
require(balanceToken >= amountMinimum, 'Insufficient token');
if (balanceToken > 0) {
token.safeTransfer(recipient, balanceToken);
}
}
function refundETH() external payable {
if (address(this).balance > 0) SafeTransferLib.safeTransferETH(msg.sender, address(this).balance);
}
}
abstract contract IWETH9 is ERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable virtual;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external virtual;
}
/// @title ERC4626 Router Base Contract
/// @author joeysantoro
abstract contract ERC4626RouterBase is IERC4626RouterBase, SelfPermit, Multicall, PeripheryPayments {
using SafeTransferLib for ERC20;
/// @inheritdoc IERC4626RouterBase
function mint(
IERC4626 vault,
address to,
uint256 shares,
uint256 maxAmountIn
) public payable virtual override returns (uint256 amountIn) {
if ((amountIn = vault.mint(shares, to)) > maxAmountIn) {
revert MaxAmountError();
}
}
/// @inheritdoc IERC4626RouterBase
function deposit(
IERC4626 vault,
address to,
uint256 amount,
uint256 minSharesOut
) public payable virtual override returns (uint256 sharesOut) {
if ((sharesOut = vault.deposit(amount, to)) < minSharesOut) {
revert MinSharesError();
}
}
/// @inheritdoc IERC4626RouterBase
function withdraw(
IERC4626 vault,
address to,
uint256 amount,
uint256 maxSharesOut
) public payable virtual override returns (uint256 sharesOut) {
if ((sharesOut = vault.withdraw(amount, to, msg.sender)) > maxSharesOut) {
revert MaxSharesError();
}
}
/// @inheritdoc IERC4626RouterBase
function redeem(
IERC4626 vault,
address to,
uint256 shares,
uint256 minAmountOut
) public payable virtual override returns (uint256 amountOut) {
if ((amountOut = vault.redeem(shares, to, msg.sender)) < minAmountOut) {
revert MinAmountError();
}
}
}
/**
@title a router which can perform multiple Turbo actions between Master and the Safes
@notice routes custom users flows between actions on the master and safes.
Extends the ERC4626RouterBase to allow for flexible combinations of actions involving ERC4626 and permit, weth, and Turbo specific actions.
Safe Creation has functions bundled with deposit (and optionally boost) because a newly created Safe address can only be known at runtime.
The caller is always atomically given the owner role of a new safe.
Authentication requires the caller to be the owner of the Safe to perform any ERC4626 method or TurboSafe requiresAuth method.
Assumes the Safe's authority gives permission to call these functions to the TurboRouter.
*/
contract TurboRouter is ERC4626RouterBase, ENSReverseRecordAuth {
using SafeTransferLib for ERC20;
TurboMaster public immutable master;
constructor (TurboMaster _master, address _owner, Authority _authority, IWETH9 weth) Auth(_owner, _authority) PeripheryPayments(weth) {
master = _master;
}
modifier authenticate(address target) {
require(msg.sender == Auth(target).owner() || Auth(target).authority().canCall(msg.sender, target, msg.sig), "NOT_AUTHED");
_;
}
function createSafe(ERC20 underlying) external returns (TurboSafe safe) {
(safe, ) = master.createSafe(underlying);
safe.setOwner(msg.sender);
}
function createSafeAndDeposit(ERC20 underlying, address to, uint256 amount, uint256 minSharesOut) external returns (TurboSafe safe) {
(safe, ) = master.createSafe(underlying);
// approve max from router to save depositor gas in future.
approve(underlying, address(safe), type(uint256).max);
super.deposit(IERC4626(address(safe)), to, amount, minSharesOut);
safe.setOwner(msg.sender);
}
function createSafeAndDepositAndBoost(
ERC20 underlying,
address to,
uint256 amount,
uint256 minSharesOut,
ERC4626 boostedVault,
uint256 boostedFeiAmount
) public returns (TurboSafe safe) {
(safe, ) = master.createSafe(underlying);
// approve max from router to save depositor gas in future.
approve(underlying, address(safe), type(uint256).max);
super.deposit(IERC4626(address(safe)), to, amount, minSharesOut);
safe.boost(boostedVault, boostedFeiAmount);
safe.setOwner(msg.sender);
}
function createSafeAndDepositAndBoostMany(
ERC20 underlying,
address to,
uint256 amount,
uint256 minSharesOut,
ERC4626[] calldata boostedVaults,
uint256[] calldata boostedFeiAmounts
) public returns (TurboSafe safe) {
(safe, ) = master.createSafe(underlying);
// approve max from router to save depositor gas in future.
approve(underlying, address(safe), type(uint256).max);
super.deposit(IERC4626(address(safe)), to, amount, minSharesOut);
unchecked {
require(boostedVaults.length == boostedFeiAmounts.length, "length");
for (uint256 i = 0; i < boostedVaults.length; i++) {
safe.boost(boostedVaults[i], boostedFeiAmounts[i]);
}
}
safe.setOwner(msg.sender);
}
function deposit(IERC4626 safe, address to, uint256 amount, uint256 minSharesOut)
public
payable
override
authenticate(address(safe))
returns (uint256)
{
return super.deposit(safe, to, amount, minSharesOut);
}
function mint(IERC4626 safe, address to, uint256 shares, uint256 maxAmountIn)
public
payable
override
authenticate(address(safe))
returns (uint256)
{
return super.mint(safe, to, shares, maxAmountIn);
}
function withdraw(IERC4626 safe, address to, uint256 amount, uint256 maxSharesOut)
public
payable
override
authenticate(address(safe))
returns (uint256)
{
return super.withdraw(safe, to, amount, maxSharesOut);
}
function redeem(IERC4626 safe, address to, uint256 shares, uint256 minAmountOut)
public
payable
override
authenticate(address(safe))
returns (uint256)
{
return super.redeem(safe, to, shares, minAmountOut);
}
function slurp(TurboSafe safe, ERC4626 vault) external authenticate(address(safe)) {
safe.slurp(vault);
}
function boost(TurboSafe safe, ERC4626 vault, uint256 feiAmount) public authenticate(address(safe)) {
safe.boost(vault, feiAmount);
}
function less(TurboSafe safe, ERC4626 vault, uint256 feiAmount) external authenticate(address(safe)) {
safe.less(vault, feiAmount);
}
function lessAll(TurboSafe safe, ERC4626 vault) external authenticate(address(safe)) {
safe.less(vault, vault.maxWithdraw(address(safe)));
}
function sweep(TurboSafe safe, address to, ERC20 token, uint256 amount) external authenticate(address(safe)) {
safe.sweep(to, token, amount);
}
function sweepAll(TurboSafe safe, address to, ERC20 token) external authenticate(address(safe)) {
safe.sweep(to, token, token.balanceOf(address(safe)));
}
function slurpAndLessAll(TurboSafe safe, ERC4626 vault) external authenticate(address(safe)) {
safe.slurp(vault);
safe.less(vault, vault.maxWithdraw(address(safe)));
}
}
/**
@title Turbo Configurer
IS INTENDED FOR MAINNET DEPLOYMENT
This contract is a helper utility to completely configure the turbo system, assuming the contracts are deployed.
The deployment should follow the logic in Deployer.sol.
Each function details its access control assumptions.
*/
contract Configurer {
/// @notice Fei DAO Timelock, to be granted TURBO_ADMIN_ROLE and GOVERN_ROLE
address constant feiDAOTimelock = 0xd51dbA7a94e1adEa403553A8235C302cEbF41a3c;
/// @notice Tribe Guardian, to be granted GUARDIAN_ROLE
address constant guardian = 0xB8f482539F2d3Ae2C9ea6076894df36D1f632775;
ERC20 fei = ERC20(0x956F47F50A910163D8BF957Cf5846D573E7f87CA);
ERC20 tribe = ERC20(0xc7283b66Eb1EB5FB86327f08e1B5816b0720212B);
/******************** ROLES ********************/
/// @notice HIGH CLEARANCE. capable of calling `gib` to impound collateral.
uint8 public constant GIBBER_ROLE = 1;
/// @notice HIGH CLEARANCE. Optional module which can interact with any user's vault by default.
uint8 public constant ROUTER_ROLE = 2;
/// @notice Capable of lessing any vault. Exposed on optional TurboSavior module.
uint8 public constant SAVIOR_ROLE = 3;
/// @notice Operational admin of Turbo, can whitelist collaterals, strategies, and configure most parameters.
uint8 public constant TURBO_ADMIN_ROLE = 4;
/// @notice Pause and security Guardian role
uint8 public constant GUARDIAN_ROLE = 5;
/// @notice HIGH CLEARANCE. Capable of critical governance functionality on TurboAdmin such as oracle upgrades.
uint8 public constant GOVERN_ROLE = 6;
/// @notice limited version of TURBO_ADMIN_ROLE which can manage collateral and vault parameters.
uint8 public constant TURBO_STRATEGIST_ROLE = 7;
/******************** CONFIGURATION ********************/
/// @notice configure the turbo timelock. Requires TIMELOCK_ADMIN_ROLE over timelock.
function configureTimelock(TimelockController turboTimelock, TurboAdmin admin) public {
turboTimelock.grantRole(turboTimelock.TIMELOCK_ADMIN_ROLE(), address(admin));
turboTimelock.grantRole(turboTimelock.EXECUTOR_ROLE(), address(admin));
turboTimelock.grantRole(turboTimelock.PROPOSER_ROLE(), address(admin));
turboTimelock.revokeRole(turboTimelock.TIMELOCK_ADMIN_ROLE(), address(this));
}
/// @notice configure the turbo authority. Requires ownership over turbo authority.
function configureAuthority(MultiRolesAuthority turboAuthority) public {
// GIBBER_ROLE
turboAuthority.setRoleCapability(GIBBER_ROLE, TurboSafe.gib.selector, true);
// TURBO_ADMIN_ROLE
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboSafe.slurp.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboSafe.less.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.createSafe.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.setBooster.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.setClerk.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.setDefaultSafeAuthority.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboMaster.sweep.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboClerk.setDefaultFeePercentage.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboClerk.setCustomFeePercentageForCollateral.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboClerk.setCustomFeePercentageForSafe.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboBooster.setFreezeStatus.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboBooster.setBoostCapForVault.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboBooster.setBoostCapForCollateral.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboSavior.setMinDebtPercentageForSaving.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMarketSupplyCaps.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMarketSupplyCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMarketBorrowCaps.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMarketBorrowCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMintPausedByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setMintPaused.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setBorrowPausedByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setBorrowPaused.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin.oracleAdd.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin.addCollateral.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._deployMarket.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._addRewardsDistributor.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setWhitelistStatuses.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setCloseFactor.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setCollateralFactor.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin._setLiquidationIncentive.selector, true);
turboAuthority.setRoleCapability(TURBO_ADMIN_ROLE, TurboAdmin.schedule.selector, true);
// GUARDIAN_ROLE
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboSafe.less.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboBooster.setFreezeStatus.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMarketSupplyCaps.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMarketSupplyCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMarketBorrowCaps.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMarketBorrowCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMintPausedByUnderlying.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setMintPaused.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setBorrowPausedByUnderlying.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setBorrowPaused.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setTransferPaused.selector, true);
turboAuthority.setRoleCapability(GUARDIAN_ROLE, TurboAdmin._setSeizePaused.selector, true);
// GOVERN_ROLE
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._setBorrowCapGuardian.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._setPauseGuardian.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin.oracleChangeAdmin.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._setWhitelistEnforcement.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._setPriceOracle.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._unsupportMarket.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin._toggleAutoImplementations.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin.scheduleSetPendingAdmin.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin.schedule.selector, true);
turboAuthority.setRoleCapability(GOVERN_ROLE, TurboAdmin.cancel.selector, true);
turboAuthority.setPublicCapability(TurboAdmin.execute.selector, true);
// TURBO_STRATEGIST_ROLE
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboAdmin.addCollateral.selector, true);
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboAdmin._setMarketSupplyCaps.selector, true);
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboAdmin._setMarketSupplyCapsByUnderlying.selector, true);
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboBooster.setBoostCapForVault.selector, true);
turboAuthority.setRoleCapability(TURBO_STRATEGIST_ROLE, TurboBooster.setBoostCapForCollateral.selector, true);
turboAuthority.setPublicCapability(TurboSavior.save.selector, true);
}
/// @notice configure the default authority. Requires ownership over default authority.
function configureDefaultAuthority(MultiRolesAuthority defaultAuthority) public {
// ROUTER_ROLE
defaultAuthority.setRoleCapability(ROUTER_ROLE, TurboSafe.boost.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, TurboSafe.less.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, TurboSafe.slurp.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, TurboSafe.sweep.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, ERC4626.deposit.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, ERC4626.mint.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, ERC4626.withdraw.selector, true);
defaultAuthority.setRoleCapability(ROUTER_ROLE, ERC4626.redeem.selector, true);
// SAVIOR_ROLE
defaultAuthority.setRoleCapability(SAVIOR_ROLE, TurboSafe.less.selector, true);
}
/// @notice configure the turbo pool through turboAdmin. TurboAdmin requires pool ownership, and Configurer requires TURBO_ADMIN_ROLE.
function configurePool(TurboAdmin turboAdmin, TurboBooster booster) public {
turboAdmin._deployMarket(
address(fei),
turboAdmin.ZERO_IRM(),
"Turbo Fei",
"fFEI",
turboAdmin.CTOKEN_IMPL(),
new bytes(0),
0,
0,
0
);
turboAdmin.addCollateral(
address(tribe),
"Turbo Tribe",
"fTRIBE",
60e16,
50_000_000e18
);
booster.setBoostCapForCollateral(tribe, 2_000_000e18); // 1M boost cap TRIBE
address[] memory users = new address[](1);
users[0] = feiDAOTimelock;
bool[] memory enabled = new bool[](1);
enabled[0] = true;
turboAdmin._setWhitelistStatuses(users, enabled);
}
/// @notice requires TURBO_ADMIN_ROLE.
function configureClerk(TurboClerk clerk) public {
clerk.setDefaultFeePercentage(75e16); // 75% default revenue split
}
/// @notice requires TURBO_ADMIN_ROLE.
function configureSavior(TurboSavior savior) public {
savior.setMinDebtPercentageForSaving(80e16); // 80%
}
/// @notice requires ownership of Turbo Authority and default authority.
function configureRoles(
MultiRolesAuthority turboAuthority,
MultiRolesAuthority defaultAuthority,
TurboRouter router,
TurboSavior savior,
TurboGibber gibber
) public {
defaultAuthority.setUserRole(address(router), ROUTER_ROLE, true);
defaultAuthority.setUserRole(address(savior), SAVIOR_ROLE, true);
turboAuthority.setUserRole(address(gibber), GIBBER_ROLE, true);
}
/// @notice requires TURBO_ADMIN_ROLE and ownership over Turbo Authority.
function configureMaster(
TurboMaster master,
TurboClerk clerk,
TurboBooster booster,
TurboAdmin admin,
MultiRolesAuthority defaultAuthority
) public {
MultiRolesAuthority turboAuthority = MultiRolesAuthority(address(master.authority()));
turboAuthority.setUserRole(address(master), TURBO_ADMIN_ROLE, true);
turboAuthority.setUserRole(address(admin), TURBO_ADMIN_ROLE, true);
turboAuthority.setUserRole(address(feiDAOTimelock), TURBO_ADMIN_ROLE, true);
turboAuthority.setUserRole(address(feiDAOTimelock), GOVERN_ROLE, true);
turboAuthority.setUserRole(address(guardian), GUARDIAN_ROLE, true);
master.setClerk(clerk);
master.setBooster(booster);
master.setDefaultSafeAuthority(defaultAuthority);
}
function configureAdmin(MultiRolesAuthority turboAuthority, Comptroller pool, TurboAdmin admin) public {
// temporarily assume ownership of pool (required by deployer)
pool._acceptAdmin();
// Temporarily grant the deployer the turbo admin role for setup
turboAuthority.setUserRole(address(this), TURBO_ADMIN_ROLE, true);
pool._setPendingAdmin(address(admin));
admin._acceptAdmin();
}
function resetOwnership(
MultiRolesAuthority defaultAuthority,
MultiRolesAuthority turboAuthority,
TimelockController turboTimelock,
address admin
) public {
if (admin != address(0)) {
turboAuthority.setUserRole(admin, TURBO_ADMIN_ROLE, true);
}
turboAuthority.setUserRole(address(this), TURBO_ADMIN_ROLE, false);
turboAuthority.setOwner(address(turboTimelock));
defaultAuthority.setOwner(address(turboTimelock));
}
} | @notice Emitted when a Safe is gibbed. @param user The user who gibbed the Safe. @param to The recipient of the impounded collateral. @param assetAmount The amount of underling tokens impounded. | event SafeGibbed(address indexed user, address indexed to, uint256 assetAmount);
| 1,253,719 | [
1,
1514,
11541,
1347,
279,
14060,
353,
314,
495,
2992,
18,
225,
729,
1021,
729,
10354,
314,
495,
2992,
326,
14060,
18,
225,
358,
1021,
8027,
434,
326,
1646,
12002,
4508,
2045,
287,
18,
225,
3310,
6275,
1021,
3844,
434,
3613,
2456,
2430,
1646,
12002,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
871,
14060,
43,
495,
2992,
12,
2867,
8808,
729,
16,
1758,
8808,
358,
16,
2254,
5034,
3310,
6275,
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,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* Originally from https://github.com/TokenMarketNet/ico
* Modified by https://www.coinfabrik.com/
*/
pragma solidity ^0.4.24;
/**
* Originally from https://github.com/TokenMarketNet/ico
* Modified by https://www.coinfabrik.com/
*/
pragma solidity ^0.4.24;
/**
* Originally from https://github.com/OpenZeppelin/zeppelin-solidity
* Modified by https://www.coinfabrik.com/
*/
pragma solidity ^0.4.24;
/**
* Interface for the standard token.
* Based on https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract EIP20Token {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool success);
function transferFrom(address from, address to, uint256 value) public returns (bool success);
function approve(address spender, uint256 value) public returns (bool success);
function allowance(address owner, address spender) public view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
** Optional functions
*
function name() public view returns (string name);
function symbol() public view returns (string symbol);
function decimals() public view returns (uint8 decimals);
*
**/
}
pragma solidity ^0.4.24;
/**
* Originally from https://github.com/OpenZeppelin/zeppelin-solidity
* Modified by https://www.coinfabrik.com/
*/
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
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(uint a, uint b) internal pure returns (uint) {
return a >= b ? a : b;
}
function min256(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
}
pragma solidity ^0.4.24;
// Interface for burning tokens
contract Burnable {
// @dev Destroys tokens for an account
// @param account Account whose tokens are destroyed
// @param value Amount of tokens to destroy
function burnTokens(address account, uint value) internal;
event Burned(address account, uint value);
}
pragma solidity ^0.4.24;
/**
* Authored by https://www.coinfabrik.com/
*/
/**
* Internal interface for the minting of tokens.
*/
contract Mintable {
/**
* @dev Mints tokens for an account
* This function should the Minted event.
*/
function mintInternal(address receiver, uint amount) internal;
/** Token supply got increased and a new owner received these tokens */
event Minted(address receiver, uint amount);
}
/**
* @title Standard token
* @dev Basic implementation of the EIP20 standard token (also known as ERC20 token).
*/
contract StandardToken is EIP20Token, Burnable, Mintable {
using SafeMath for uint;
uint private total_supply;
mapping(address => uint) private balances;
mapping(address => mapping (address => uint)) private allowed;
function totalSupply() public view returns (uint) {
return total_supply;
}
/**
* @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, uint value) public returns (bool success) {
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 account The address whose balance is to be queried.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address account) public view returns (uint balance) {
return balances[account];
}
/**
* @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 uint the amout of tokens to be transfered
*/
function transferFrom(address from, address to, uint value) public returns (bool success) {
uint 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);
// SafeMath uses assert instead of require though, beware when using an analysis tool
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowance.sub(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev 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, 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;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param account address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address account, address spender) public view returns (uint remaining) {
return allowed[account][spender];
}
/**
* Atomic increment of approved spending
*
* Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
*/
function addApproval(address spender, uint addedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][spender];
allowed[msg.sender][spender] = oldValue.add(addedValue);
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
/**
* Atomic decrement of approved spending.
*
* Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*/
function subApproval(address spender, uint subtractedValue) public returns (bool success) {
uint oldVal = allowed[msg.sender][spender];
if (subtractedValue > oldVal) {
allowed[msg.sender][spender] = 0;
} else {
allowed[msg.sender][spender] = oldVal.sub(subtractedValue);
}
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
/**
* @dev Provides an internal function for destroying tokens. Useful for upgrades.
*/
function burnTokens(address account, uint value) internal {
balances[account] = balances[account].sub(value);
total_supply = total_supply.sub(value);
emit Transfer(account, 0, value);
emit Burned(account, value);
}
/**
* @dev Provides an internal minting function.
*/
function mintInternal(address receiver, uint amount) internal {
total_supply = total_supply.add(amount);
balances[receiver] = balances[receiver].add(amount);
emit Minted(receiver, amount);
// Beware: Address zero may be used for special transactions in a future fork.
// This will make the mint transaction appear in EtherScan.io
// We can remove this after there is a standardized minting event
emit Transfer(0, receiver, amount);
}
}
pragma solidity ^0.4.24;
/**
* Originally from https://github.com/OpenZeppelin/zeppelin-solidity
* Modified by https://www.coinfabrik.com/
*/
/**
* @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.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* Define interface for releasing the token transfer after a successful crowdsale.
*/
contract ReleasableToken is StandardToken, Ownable {
/* The finalizer contract that allows lifting the transfer limits on this token */
address public releaseAgent;
/** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/
bool public released = false;
/** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */
mapping (address => bool) public transferAgents;
/**
* Set the contract that can call release and make the token transferable.
*
* Since the owner of this contract is (or should be) the crowdsale,
* it can only be called by a corresponding exposed API in the crowdsale contract in case of input error.
*/
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
// We don't do interface check here as we might want to have a normal wallet address to act as a release agent.
releaseAgent = addr;
}
/**
* Owner can allow a particular address (e.g. a crowdsale contract) to transfer tokens despite the lock up period.
*/
function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public {
transferAgents[addr] = state;
}
/**
* One way function to release the tokens into the wild.
*
* Can be called only from the release agent that should typically be the finalize agent ICO contract.
* In the scope of the crowdsale, it is only called if the crowdsale has been a success (first milestone reached).
*/
function releaseTokenTransfer() public onlyReleaseAgent {
released = true;
}
/**
* Limit token transfer until the crowdsale is over.
*/
modifier canTransfer(address sender) {
require(released || transferAgents[sender]);
_;
}
/** The function can be called only before or after the tokens have been released */
modifier inReleaseState(bool releaseState) {
require(releaseState == released);
_;
}
/** The function can be called only by a whitelisted release agent. */
modifier onlyReleaseAgent() {
require(msg.sender == releaseAgent);
_;
}
/** We restrict transfer by overriding it */
function transfer(address to, uint value) public canTransfer(msg.sender) returns (bool success) {
// Call StandardToken.transfer()
return super.transfer(to, value);
}
/** We restrict transferFrom by overriding it */
function transferFrom(address from, address to, uint value) public canTransfer(from) returns (bool success) {
// Call StandardToken.transferForm()
return super.transferFrom(from, to, value);
}
}
pragma solidity ^0.4.24;
/**
* First envisioned by Golem and Lunyr projects.
* Originally from https://github.com/TokenMarketNet/ico
* Modified by https://www.coinfabrik.com/
*/
pragma solidity ^0.4.24;
/**
* Inspired by Lunyr.
* Originally from https://github.com/TokenMarketNet/ico
*/
/**
* Upgrade agent transfers tokens to a new contract.
* Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting.
*
* The Upgrade agent is the interface used to implement a token
* migration in the case of an emergency.
* The function upgradeFrom has to implement the part of the creation
* of new tokens on behalf of the user doing the upgrade.
*
* The new token can implement this interface directly, or use.
*/
contract UpgradeAgent {
/** This value should be the same as the original token's total supply */
uint public originalSupply;
/** Interface to ensure the contract is correctly configured */
function isUpgradeAgent() public pure returns (bool) {
return true;
}
/**
Upgrade an account
When the token contract is in the upgrade status the each user will
have to call `upgrade(value)` function from UpgradeableToken.
The upgrade function adjust the balance of the user and the supply
of the previous token and then call `upgradeFrom(value)`.
The UpgradeAgent is the responsible to create the tokens for the user
in the new contract.
* @param from Account to upgrade.
* @param value Tokens to upgrade.
*/
function upgradeFrom(address from, uint value) public;
}
/**
* A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision.
*
*/
contract UpgradeableToken is EIP20Token, Burnable {
using SafeMath for uint;
/** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */
address public upgradeMaster;
/** The next contract where the tokens will be migrated. */
UpgradeAgent public upgradeAgent;
/** How many tokens we have upgraded by now. */
uint public totalUpgraded = 0;
/**
* Upgrade states.
*
* - NotAllowed: The child contract has not reached a condition where the upgrade can begin
* - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet
* - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet. This allows changing the upgrade agent while there is time.
* - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens
*
*/
enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
/**
* Somebody has upgraded some of his tokens.
*/
event Upgrade(address indexed from, address to, uint value);
/**
* New upgrade agent available.
*/
event UpgradeAgentSet(address agent);
/**
* Do not allow construction without upgrade master set.
*/
constructor(address master) internal {
setUpgradeMaster(master);
}
/**
* Allow the token holder to upgrade some of their tokens to a new contract.
*/
function upgrade(uint value) public {
UpgradeState state = getUpgradeState();
// Ensure it's not called in a bad state
require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading);
// Validate input value.
require(value != 0);
// Upgrade agent reissues the tokens
upgradeAgent.upgradeFrom(msg.sender, value);
// Take tokens out from circulation
burnTokens(msg.sender, value);
totalUpgraded = totalUpgraded.add(value);
emit Upgrade(msg.sender, upgradeAgent, value);
}
/**
* Set an upgrade agent that handles the upgrade process
*/
function setUpgradeAgent(address agent) onlyMaster external {
// Check whether the token is in a state that we could think of upgrading
require(canUpgrade());
require(agent != 0x0);
// Upgrade has already begun for an agent
require(getUpgradeState() != UpgradeState.Upgrading);
upgradeAgent = UpgradeAgent(agent);
// Bad interface
require(upgradeAgent.isUpgradeAgent());
// Make sure that token supplies match in source and target
require(upgradeAgent.originalSupply() == totalSupply());
emit UpgradeAgentSet(upgradeAgent);
}
/**
* Get the state of the token upgrade.
*/
function getUpgradeState() public view returns(UpgradeState) {
if (!canUpgrade()) return UpgradeState.NotAllowed;
else if (address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent;
else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
/**
* Change the upgrade master.
*
* This allows us to set a new owner for the upgrade mechanism.
*/
function changeUpgradeMaster(address new_master) onlyMaster public {
setUpgradeMaster(new_master);
}
/**
* Internal upgrade master setter.
*/
function setUpgradeMaster(address new_master) private {
require(new_master != 0x0);
upgradeMaster = new_master;
}
/**
* Child contract can override to provide the condition in which the upgrade can begin.
*/
function canUpgrade() public view returns(bool) {
return true;
}
modifier onlyMaster() {
require(msg.sender == upgradeMaster);
_;
}
}
pragma solidity ^0.4.24;
/**
* Authored by https://www.coinfabrik.com/
*/
// This contract aims to provide an inheritable way to recover tokens from a contract not meant to hold tokens
// To use this contract, have your token-ignoring contract inherit this one and implement getLostAndFoundMaster to decide who can move lost tokens.
// Of course, this contract imposes support costs upon whoever is the lost and found master.
contract LostAndFoundToken {
/**
* @return Address of the account that handles movements.
*/
function getLostAndFoundMaster() internal view returns (address);
/**
* @param agent Address that will be able to move tokens with transferFrom
* @param tokens Amount of tokens approved for transfer
* @param token_contract Contract of the token
*/
function enableLostAndFound(address agent, uint tokens, EIP20Token token_contract) public {
require(msg.sender == getLostAndFoundMaster());
// We use approve instead of transfer to minimize the possibility of the lost and found master
// getting them stuck in another address by accident.
token_contract.approve(agent, tokens);
}
}
pragma solidity ^0.4.24;
/**
* Originally from https://github.com/TokenMarketNet/ico
* Modified by https://www.coinfabrik.com/
*/
/**
* A public interface to increase the supply of a token.
*
* This allows uncapped crowdsale by dynamically increasing the supply when money pours in.
* Only mint agents, usually contracts whitelisted by the owner, can mint new tokens.
*
*/
contract MintableToken is Mintable, Ownable {
using SafeMath for uint;
bool public mintingFinished = false;
/** List of agents that are allowed to create new tokens */
mapping (address => bool) public mintAgents;
event MintingAgentChanged(address addr, bool state);
constructor(uint initialSupply, address multisig, bool mintable) internal {
require(multisig != address(0));
// Cannot create a token without supply and no minting
require(mintable || initialSupply != 0);
// Create initially all balance on the team multisig
if (initialSupply > 0)
mintInternal(multisig, initialSupply);
// No more new supply allowed after the token creation
mintingFinished = !mintable;
}
/**
* Create new tokens and allocate them to an address.
*
* Only callable by a mint agent (e.g. crowdsale contract).
*/
function mint(address receiver, uint amount) onlyMintAgent canMint public {
mintInternal(receiver, amount);
}
/**
* Owner can allow a crowdsale contract to mint new tokens.
*/
function setMintAgent(address addr, bool state) onlyOwner canMint public {
mintAgents[addr] = state;
emit MintingAgentChanged(addr, state);
}
modifier onlyMintAgent() {
// Only mint agents are allowed to mint new tokens
require(mintAgents[msg.sender]);
_;
}
/** Make sure we are not done yet. */
modifier canMint() {
require(!mintingFinished);
_;
}
}
/**
* A crowdsale token.
*
* An ERC-20 token designed specifically for crowdsales with investor protection and further development path.
*
* - The token transfer() is disabled until the crowdsale is over
* - The token contract gives an opt-in upgrade path to a new contract
* - The same token can be part of several crowdsales through the approve() mechanism
* - The token can be capped (supply set in the constructor) or uncapped (crowdsale contract can mint new tokens)
* - ERC20 tokens transferred to this contract can be recovered by a lost and found master
*
*/
contract CrowdsaleToken is ReleasableToken, MintableToken, UpgradeableToken, LostAndFoundToken {
string public name = "Kryptobits";
string public symbol = "KBE";
uint8 public decimals;
address public lost_and_found_master;
/**
* Construct the token.
*
* This token must be created through a team multisig wallet, so that it is owned by that wallet.
*
* @param initial_supply How many tokens we start with.
* @param token_decimals Number of decimal places.
* @param team_multisig Address of the multisig that receives the initial supply and is set as the upgrade master.
* @param token_retriever Address of the account that handles ERC20 tokens that were accidentally sent to this contract.
*/
constructor(uint initial_supply, uint8 token_decimals, address team_multisig, address token_retriever) public
UpgradeableToken(team_multisig) MintableToken(initial_supply, team_multisig, true) {
require(token_retriever != address(0));
decimals = token_decimals;
lost_and_found_master = token_retriever;
}
/**
* When token is released to be transferable, prohibit new token creation.
*/
function releaseTokenTransfer() public onlyReleaseAgent {
mintingFinished = true;
super.releaseTokenTransfer();
}
/**
* Allow upgrade agent functionality to kick in only if the crowdsale was a success.
*/
function canUpgrade() public view returns(bool) {
return released && super.canUpgrade();
}
function burn(uint value) public {
burnTokens(msg.sender, value);
}
function getLostAndFoundMaster() internal view returns(address) {
return lost_and_found_master;
}
} | * @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;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
owner = newOwner;
}
}
| 1,243,499 | [
1,
5460,
429,
225,
1021,
14223,
6914,
6835,
711,
392,
3410,
1758,
16,
471,
8121,
5337,
6093,
3325,
4186,
16,
333,
9330,
5032,
326,
4471,
434,
315,
1355,
4371,
9654,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
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,
14223,
6914,
288,
203,
225,
1758,
1071,
3410,
31,
203,
203,
203,
203,
225,
3885,
1435,
1071,
288,
203,
565,
3410,
273,
1234,
18,
15330,
31,
203,
225,
289,
203,
203,
203,
225,
9606,
1338,
5541,
1435,
288,
203,
565,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
565,
389,
31,
203,
225,
289,
203,
203,
203,
225,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1338,
5541,
1071,
288,
203,
565,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
10019,
203,
565,
3410,
273,
394,
5541,
31,
203,
225,
289,
203,
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
] |
pragma solidity 0.6.6;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./interfaces/ITetherswapFactory.sol";
import "./interfaces/ITetherswapPriceOracle.sol";
import "./libraries/SafeMathTetherswap.sol";
import "./libraries/TransferHelper.sol";
import "./TetherswapPair.sol";
contract TetherswapFactory is ITetherswapFactory, ReentrancyGuard {
using SafeMathTetherswap for uint256;
address public immutable override USDT;
address public immutable override WETH;
address public immutable override YFTE;
address public override governance;
address public override treasury;
address public override priceOracle;
uint256 public override usdtListingFeeInUsd;
uint256 public override wethListingFeeInUsd;
uint256 public override yfteListingFeeInUsd;
uint256 public override treasuryListingFeeShare = 1000000;
uint256 public override minListingLockupAmountInUsd;
uint256 public override targetListingLockupAmountInUsd;
uint256 public override minListingLockupPeriod;
uint256 public override targetListingLockupPeriod;
uint256 public override lockupAmountListingFeeDiscountShare;
uint256 public override defaultUsdtTradingFeePercent = 2500; // 0.2500%
uint256 public override defaultNonUsdtTradingFeePercent = 3000; // 0.3000%
uint256 public override treasuryProtocolFeeShare = 1000000; // 100%
uint256 public override protocolFeeFractionInverse; // protocol fee off initially
uint256 public override maxSlippagePercent;
uint256 public override maxSlippageBlocks = 1;
mapping(address => mapping(address => address)) public override getPair;
mapping(address => mapping(address => bool)) public override approvedPair;
address[] public override allPairs;
modifier onlyGovernance() {
require(msg.sender == governance);
_;
}
constructor(
address _governance,
address _treasury,
address _priceOracle,
uint256 _usdtListingFeeInUsd,
uint256 _wethListingFeeInUsd,
uint256 _yfteListingFeeInUsd,
uint256 _treasuryListingFeeShare,
uint256 _minListingLockupAmountInUsd,
uint256 _targetListingLockupAmountInUsd,
uint256 _minListingLockupPeriod,
uint256 _targetListingLockupPeriod,
uint256 _lockupAmountListingFeeDiscountShare,
address _usdtToken,
address _WETH,
address _yfteToken
) public {
governance = _governance;
treasury = _treasury;
priceOracle = _priceOracle;
usdtListingFeeInUsd = _usdtListingFeeInUsd;
wethListingFeeInUsd = _wethListingFeeInUsd;
yfteListingFeeInUsd = _yfteListingFeeInUsd;
treasuryListingFeeShare = _treasuryListingFeeShare;
_setTargetListingLockupAmountInUsd(_targetListingLockupAmountInUsd);
_setMinListingLockupAmountInUsd(_minListingLockupAmountInUsd);
_setTargetListingLockupPeriod(_targetListingLockupPeriod);
_setMinListingLockupPeriod(_minListingLockupPeriod);
lockupAmountListingFeeDiscountShare = _lockupAmountListingFeeDiscountShare;
USDT = _usdtToken;
WETH = _WETH;
YFTE = _yfteToken;
}
function allPairsLength() external view override returns (uint256) {
return allPairs.length;
}
function _validatePair(address tokenA, address tokenB)
private
view
returns (address token0, address token1)
{
require(tokenA != tokenB);
(token0, token1) = tokenA < tokenB
? (tokenA, tokenB)
: (tokenB, tokenA);
require(token0 != address(0));
require(getPair[token0][token1] == address(0)); // single check is sufficient
}
function _createPair(address token0, address token1)
private
returns (address pair)
{
{
bytes memory bytecode = type(TetherswapPair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
}
TetherswapPair(pair).initialize(
token0,
token1,
token0 == address(USDT) || token1 == address(USDT)
? defaultUsdtTradingFeePercent
: defaultNonUsdtTradingFeePercent
);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function approvePairViaGovernance(address tokenA, address tokenB)
external
override
onlyGovernance
nonReentrant
{
(address token0, address token1) = _validatePair(tokenA, tokenB);
approvedPair[token0][token1] = true;
}
function _payListingFee(
address listingFeeToken,
uint256 lockupAmountInUsd,
uint256 lockupPeriod
) private {
require(
listingFeeToken == USDT ||
listingFeeToken == WETH ||
listingFeeToken == YFTE
);
uint256 listingFeeTokenAmount;
if (listingFeeToken == USDT) {
listingFeeTokenAmount = ITetherswapPriceOracle(priceOracle)
.calculateTokenAmountFromUsdAmount(USDT, usdtListingFeeInUsd);
} else if (listingFeeToken == WETH) {
listingFeeTokenAmount = ITetherswapPriceOracle(priceOracle)
.calculateTokenAmountFromUsdAmount(WETH, wethListingFeeInUsd);
} else if (listingFeeToken == YFTE) {
ITetherswapPriceOracle(priceOracle).update();
listingFeeTokenAmount = ITetherswapPriceOracle(priceOracle)
.calculateTokenAmountFromUsdAmount(YFTE, yfteListingFeeInUsd);
}
uint256 discount;
if (targetListingLockupAmountInUsd > minListingLockupAmountInUsd) {
discount =
lockupAmountListingFeeDiscountShare.mul(
lockupAmountInUsd.sub(minListingLockupAmountInUsd)
) /
(
targetListingLockupAmountInUsd.sub(
minListingLockupAmountInUsd
)
);
}
if (targetListingLockupPeriod > minListingLockupPeriod) {
discount = discount.add(
(uint256(1000000).sub(lockupAmountListingFeeDiscountShare)).mul(
lockupPeriod.sub(minListingLockupPeriod)
) / (targetListingLockupPeriod.sub(minListingLockupPeriod))
);
}
uint256 discountedListingFeeTokenAmount =
listingFeeTokenAmount.mul(uint256(1000000).sub(discount)) / 1000000;
TransferHelper.safeTransferFrom(
listingFeeToken,
msg.sender,
treasury,
discountedListingFeeTokenAmount.mul(treasuryListingFeeShare) /
1000000
);
TransferHelper.safeTransferFrom(
listingFeeToken,
msg.sender,
governance,
discountedListingFeeTokenAmount.mul(
uint256(1000000).sub(treasuryListingFeeShare)
) / 1000000
);
}
function createPair(
address newToken,
uint256 newTokenAmount,
address lockupToken, // USDT or WETH, or part of a governance-approved pair
uint256 lockupTokenAmount,
uint256 lockupPeriod,
address listingFeeToken // can be zero address if governance-approved pair
) external override nonReentrant returns (address pair) {
require(msg.sender != governance);
require(newToken != address(0) && lockupToken != address(0));
(address token0, address token1) = _validatePair(newToken, lockupToken);
if (!approvedPair[token0][token1]) {
require(
lockupToken == USDT || lockupToken == WETH,
"TetherswapFactory: Pair Not Approved."
);
require(lockupPeriod >= minListingLockupPeriod);
uint256 lockupAmountInUsd =
ITetherswapPriceOracle(priceOracle)
.calculateUsdAmountFromTokenAmount(
lockupToken,
lockupTokenAmount
);
require(lockupAmountInUsd >= minListingLockupAmountInUsd);
_payListingFee(listingFeeToken, lockupAmountInUsd, lockupPeriod);
}
pair = _createPair(token0, token1);
uint256 liquidity;
if (newTokenAmount > 0 && lockupTokenAmount > 0) {
TransferHelper.safeTransferFrom(
newToken,
msg.sender,
pair,
newTokenAmount
);
TransferHelper.safeTransferFrom(
lockupToken,
msg.sender,
pair,
lockupTokenAmount
);
liquidity = TetherswapPair(pair).mint(msg.sender);
}
if (
!approvedPair[token0][token1] &&
lockupTokenAmount > 0 &&
lockupPeriod > 0
) {
TetherswapPair(pair).listingLock(
msg.sender,
lockupPeriod,
liquidity
);
}
}
function setPriceOracle(address _priceOracle)
external
override
onlyGovernance
{
priceOracle = _priceOracle;
}
function setTreasury(address _treasury) external override onlyGovernance {
treasury = _treasury;
}
function setGovernance(address _governance)
external
override
onlyGovernance
{
require(_governance != address(0));
governance = _governance;
}
function setTreasuryProtocolFeeShare(uint256 _treasuryProtocolFeeShare)
external
override
onlyGovernance
{
require(_treasuryProtocolFeeShare <= 1000000);
treasuryProtocolFeeShare = _treasuryProtocolFeeShare;
}
function setProtocolFeeFractionInverse(uint256 _protocolFeeFractionInverse)
external
override
onlyGovernance
{
// max 50% of trading fee (2/1 * 1000)
require(
_protocolFeeFractionInverse >= 2000 ||
_protocolFeeFractionInverse == 0
);
protocolFeeFractionInverse = _protocolFeeFractionInverse;
}
function setUsdtListingFeeInUsd(uint256 _usdtListingFeeInUsd)
external
override
onlyGovernance
{
usdtListingFeeInUsd = _usdtListingFeeInUsd;
}
function setWethListingFeeInUsd(uint256 _wethListingFeeInUsd)
external
override
onlyGovernance
{
wethListingFeeInUsd = _wethListingFeeInUsd;
}
function setYfteListingFeeInUsd(uint256 _yfteListingFeeInUsd)
external
override
onlyGovernance
{
yfteListingFeeInUsd = _yfteListingFeeInUsd;
}
function setTreasuryListingFeeShare(uint256 _treasuryListingFeeShare)
external
override
onlyGovernance
{
require(_treasuryListingFeeShare <= 1000000);
treasuryListingFeeShare = _treasuryListingFeeShare;
}
function _setMinListingLockupAmountInUsd(
uint256 _minListingLockupAmountInUsd
) private {
require(_minListingLockupAmountInUsd <= targetListingLockupAmountInUsd);
if (_minListingLockupAmountInUsd > 0) {
// needs to be at least 1000 due to TetherswapPair MINIMUM_LIQUIDITY subtraction
require(_minListingLockupAmountInUsd >= 1000);
}
minListingLockupAmountInUsd = _minListingLockupAmountInUsd;
}
function setMinListingLockupAmountInUsd(
uint256 _minListingLockupAmountInUsd
) external override onlyGovernance {
_setMinListingLockupAmountInUsd(_minListingLockupAmountInUsd);
}
function _setTargetListingLockupAmountInUsd(
uint256 _targetListingLockupAmountInUsd
) private {
require(_targetListingLockupAmountInUsd >= minListingLockupAmountInUsd);
targetListingLockupAmountInUsd = _targetListingLockupAmountInUsd;
}
function setTargetListingLockupAmountInUsd(
uint256 _targetListingLockupAmountInUsd
) external override onlyGovernance {
_setTargetListingLockupAmountInUsd(_targetListingLockupAmountInUsd);
}
function _setMinListingLockupPeriod(uint256 _minListingLockupPeriod)
private
{
require(_minListingLockupPeriod <= targetListingLockupPeriod);
minListingLockupPeriod = _minListingLockupPeriod;
}
function setMinListingLockupPeriod(uint256 _minListingLockupPeriod)
external
override
onlyGovernance
{
_setMinListingLockupPeriod(_minListingLockupPeriod);
}
function _setTargetListingLockupPeriod(uint256 _targetListingLockupPeriod)
private
{
require(_targetListingLockupPeriod >= minListingLockupPeriod);
targetListingLockupPeriod = _targetListingLockupPeriod;
}
function setTargetListingLockupPeriod(uint256 _targetListingLockupPeriod)
external
override
onlyGovernance
{
_setTargetListingLockupPeriod(_targetListingLockupPeriod);
}
function setLockupAmountListingFeeDiscountShare(
uint256 _lockupAmountListingFeeDiscountShare
) external override onlyGovernance {
require(_lockupAmountListingFeeDiscountShare <= 1000000);
lockupAmountListingFeeDiscountShare = _lockupAmountListingFeeDiscountShare;
}
function setDefaultUsdtTradingFeePercent(
uint256 _defaultUsdtTradingFeePercent
) external override onlyGovernance {
// max 1%
require(_defaultUsdtTradingFeePercent <= 10000);
defaultUsdtTradingFeePercent = _defaultUsdtTradingFeePercent;
}
function setDefaultNonUsdtTradingFeePercent(
uint256 _defaultNonUsdtTradingFeePercent
) external override onlyGovernance {
// max 1%
require(_defaultNonUsdtTradingFeePercent <= 10000);
defaultNonUsdtTradingFeePercent = _defaultNonUsdtTradingFeePercent;
}
function setMaxSlippagePercent(uint256 _maxSlippagePercent)
external
override
onlyGovernance
{
// max 100%
require(_maxSlippagePercent <= 100);
maxSlippagePercent = _maxSlippagePercent;
}
function setMaxSlippageBlocks(uint256 _maxSlippageBlocks)
external
override
onlyGovernance
{
// min 1 block, max 7 days (15s/block)
require(_maxSlippageBlocks >= 1 && _maxSlippageBlocks <= 40320);
maxSlippageBlocks = _maxSlippageBlocks;
}
}
// 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;
}
}
pragma solidity 0.6.6;
interface ITetherswapFactory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256 pairNum
);
function USDT() external view returns (address);
function WETH() external view returns (address);
function YFTE() external view returns (address);
function governance() external view returns (address);
function treasury() external view returns (address);
function priceOracle() external view returns (address);
// USD amounts should be 8 dp precision
// frontend should approve transfer of higher amount (e.g. 1.1x) due to price fluctuations
function usdtListingFeeInUsd() external view returns (uint256);
function wethListingFeeInUsd() external view returns (uint256);
function yfteListingFeeInUsd() external view returns (uint256);
// need to divide share by 1,000,000 e.g. 100,000 is 10%
// the rest goes to governance
function treasuryListingFeeShare() external view returns (uint256);
function minListingLockupAmountInUsd() external view returns (uint256);
// if lockup amount is set to this or more, the lockup amount proportion of listing fee discount is fully unlocked
// if less than this amount, then lockup amount proportion of listing fee discount is linearly interpolated from the distance between min and target lockup amounts e.g. 60% towards target from min means 60% of lockup amount discount
function targetListingLockupAmountInUsd() external view returns (uint256);
// in seconds since unix epoch
// min lockup period for the listing lockup amount
function minListingLockupPeriod() external view returns (uint256);
// in seconds since unix epoch
// if lockup period is set to this or longer, the lockup time proportion of listing fee discount is fully unlocked
// if less than this period, then lockup time proportion of listing fee discount is linearly interpolated from the distance between min and target lockup times e.g. 60% towards target from min means 60% of lockup time discount
function targetListingLockupPeriod() external view returns (uint256);
// need to divide share by 1,000,000 e.g. 100,000 is 10%
// rest of listing fee discount is determined by lockup period
function lockupAmountListingFeeDiscountShare()
external
view
returns (uint256);
// need to divide fee percents by 1,000,000 e.g. 3000 is 0.3000%
function defaultUsdtTradingFeePercent() external view returns (uint256);
function defaultNonUsdtTradingFeePercent() external view returns (uint256);
// need to divide share by 1,000,000 e.g. 100,000 is 10%
// the rest goes to governance
function treasuryProtocolFeeShare() external view returns (uint256);
// inverse of protocol fee fraction, then multiplied by 1000.
// e.g. if protocol fee is 3/7th of trading fee, then value = 7/3 * 1000 = 2333
// set to 0 to disable protocol fee
function protocolFeeFractionInverse() external view returns (uint256);
// need to divide by 100 e.g. 50 is 50%
function maxSlippagePercent() external view returns (uint256);
// max slippage resets after this many blocks
function maxSlippageBlocks() external view returns (uint256);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function approvedPair(address tokenA, address tokenB)
external
view
returns (bool approved);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function approvePairViaGovernance(address tokenA, address tokenB) external;
function createPair(
address newToken,
uint256 newTokenAmount,
address lockupToken, // USDT or WETH
uint256 lockupTokenAmount,
uint256 lockupPeriod,
address listingFeeToken
) external returns (address pair);
function setPriceOracle(address) external;
function setTreasury(address) external;
function setGovernance(address) external;
function setTreasuryProtocolFeeShare(uint256) external;
function setProtocolFeeFractionInverse(uint256) external;
function setUsdtListingFeeInUsd(uint256) external;
function setWethListingFeeInUsd(uint256) external;
function setYfteListingFeeInUsd(uint256) external;
function setTreasuryListingFeeShare(uint256) external;
function setMinListingLockupAmountInUsd(uint256) external;
function setTargetListingLockupAmountInUsd(uint256) external;
function setMinListingLockupPeriod(uint256) external;
function setTargetListingLockupPeriod(uint256) external;
function setLockupAmountListingFeeDiscountShare(uint256) external;
function setDefaultUsdtTradingFeePercent(uint256) external;
function setDefaultNonUsdtTradingFeePercent(uint256) external;
function setMaxSlippagePercent(uint256) external;
function setMaxSlippageBlocks(uint256) external;
}
pragma solidity 0.6.6;
interface ITetherswapPriceOracle {
function update() external;
// tokenAmount is to 18 dp, usdAmount is to 8 dp
// token must be USDT / WETH / YFTE
function calculateTokenAmountFromUsdAmount(address token, uint256 usdAmount)
external
view
returns (uint256 tokenAmount);
// token must be USDT / WETH
function calculateUsdAmountFromTokenAmount(
address token,
uint256 tokenAmount
) external view returns (uint256 usdAmount);
}
pragma solidity 0.6.6;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathTetherswap {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
}
pragma solidity 0.6.6;
// 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,
uint256 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,
uint256 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,
uint256 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, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "TransferHelper: ETH_TRANSFER_FAILED");
}
}
pragma solidity 0.6.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./libraries/Math.sol";
import "./libraries/SafeMathTetherswap.sol";
import "./libraries/UQ112x112.sol";
import "./interfaces/ITetherswapCallee.sol";
import "./interfaces/ITetherswapFactory.sol";
import "./interfaces/ITetherswapPair.sol";
contract TetherswapPair is ITetherswapPair, ReentrancyGuard {
using SafeMathTetherswap for uint256;
using UQ112x112 for uint224;
string public constant override name = "Tetherswap LP Token";
string public constant override symbol = "TLP";
uint8 public constant override decimals = 18;
uint256 public override totalSupply;
mapping(address => uint256) public override balanceOf;
mapping(address => mapping(address => uint256)) public override allowance;
bytes32 public override DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant override PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public override nonces;
uint256 public constant override MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR =
bytes4(keccak256(bytes("transfer(address,uint256)")));
mapping(address => uint256) public override addressToLockupExpiry;
mapping(address => uint256) public override addressToLockupAmount;
address public override factory;
address public override token0;
address public override token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint256 public override price0CumulativeLast;
uint256 public override price1CumulativeLast;
uint256 public override kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint256 public override tradingFeePercent; // need to divide by 1,000,000, e.g. 3000 = 0.3%
uint256 public override lastSlippageBlocks;
uint256 public override priceAtLastSlippageBlocks;
uint256 public override lastSwapPrice;
modifier onlyGovernance() {
require(
msg.sender == ITetherswapFactory(factory).governance(),
"Pair: FORBIDDEN"
);
_;
}
constructor() public {
factory = msg.sender;
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(name)),
keccak256(bytes("1")),
chainId,
address(this)
)
);
}
// called once by the factory at time of deployment
function initialize(
address _token0,
address _token1,
uint256 _tradingFeePercent
) external override {
require(msg.sender == factory, "Pair: FORBIDDEN"); // sufficient check
token0 = _token0;
token1 = _token1;
tradingFeePercent = _tradingFeePercent;
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(
address owner,
address spender,
uint256 value
) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(
address from,
address to,
uint256 value
) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value)
external
override
returns (bool)
{
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value)
external
override
returns (bool)
{
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external override returns (bool) {
if (allowance[from][msg.sender] != uint256(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(
value
);
}
_transfer(from, to, value);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(deadline >= block.timestamp, "Pair: EXPIRED");
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
recoveredAddress != address(0) && recoveredAddress == owner,
"Pair: INVALID_SIGNATURE"
);
_approve(owner, spender, value);
}
function getReserves()
public
view
override
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
)
{
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(
address token,
address to,
uint256 value
) private {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"Pair: TRANSFER_FAILED"
);
}
// update reserves and, on the first call per block, price accumulators
function _update(
uint256 balance0,
uint256 balance1,
uint112 _reserve0,
uint112 _reserve1
) private {
require(
balance0 <= uint112(-1) && balance1 <= uint112(-1),
"Pair: OVERFLOW"
);
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast +=
uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) *
timeElapsed;
price1CumulativeLast +=
uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) *
timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
function _mintFee(uint112 _reserve0, uint112 _reserve1)
private
returns (bool feeOn)
{
uint256 protocolFeeFractionInverse =
ITetherswapFactory(factory).protocolFeeFractionInverse();
feeOn = protocolFeeFractionInverse != 0;
uint256 _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint256 rootK = Math.sqrt(uint256(_reserve0).mul(_reserve1));
uint256 rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint256 liquidity =
totalSupply.mul(rootK.sub(rootKLast)).mul(1000) /
(
(
rootK.mul(
protocolFeeFractionInverse.sub(1000)
)
)
.add(rootKLast.mul(1000))
);
if (liquidity > 0) {
ITetherswapFactory TetherswapFactory =
ITetherswapFactory(factory);
uint256 treasuryProtocolFeeShare =
TetherswapFactory.treasuryProtocolFeeShare();
_mint(
TetherswapFactory.treasury(),
liquidity.mul(treasuryProtocolFeeShare) / 1000000
);
_mint(
TetherswapFactory.governance(),
liquidity.mul(
uint256(1000000).sub(treasuryProtocolFeeShare)
) / 1000000
);
}
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to)
public
override
nonReentrant
returns (uint256 liquidity)
{
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
uint256 balance0 = IERC20(token0).balanceOf(address(this));
uint256 balance1 = IERC20(token1).balanceOf(address(this));
uint256 amount0 = balance0.sub(_reserve0);
uint256 amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(
amount0.mul(_totalSupply) / _reserve0,
amount1.mul(_totalSupply) / _reserve1
);
}
require(liquidity > 0, "Pair: INSUFFICIENT_LIQUIDITY_MINTED");
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
function _lock(
address locker,
uint256 lockupPeriod,
uint256 liquidityLockupAmount
) private {
if (lockupPeriod == 0 && liquidityLockupAmount == 0) return;
if (addressToLockupExpiry[locker] == 0) {
// not currently locked
require(lockupPeriod > 0, "Pair: ZERO_LOCKUP_PERIOD");
require(liquidityLockupAmount > 0, "Pair: ZERO_LOCKUP_AMOUNT");
addressToLockupExpiry[locker] = block.timestamp.add(lockupPeriod);
} else {
// locking when already locked will extend lockup period
addressToLockupExpiry[locker] = addressToLockupExpiry[locker].add(
lockupPeriod
);
}
addressToLockupAmount[locker] = addressToLockupAmount[locker].add(
liquidityLockupAmount
);
_transfer(locker, address(this), liquidityLockupAmount);
emit Lock(locker, lockupPeriod, liquidityLockupAmount);
}
// called once by the factory at time of deployment
function listingLock(
address lister,
uint256 lockupPeriod,
uint256 liquidityLockupAmount
) external override {
require(msg.sender == factory, "Pair: FORBIDDEN");
_lock(lister, lockupPeriod, liquidityLockupAmount);
}
function lock(uint256 lockupPeriod, uint256 liquidityLockupAmount)
external
override
{
_lock(msg.sender, lockupPeriod, liquidityLockupAmount);
}
function unlock() external override {
require(
addressToLockupExpiry[msg.sender] <= block.timestamp,
"Pair: BEFORE_EXPIRY"
);
_transfer(address(this), msg.sender, addressToLockupAmount[msg.sender]);
emit Unlock(msg.sender, addressToLockupAmount[msg.sender]);
addressToLockupAmount[msg.sender] = 0;
addressToLockupExpiry[msg.sender] = 0;
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to)
external
override
nonReentrant
returns (uint256 amount0, uint256 amount1)
{
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint256 balance0 = IERC20(_token0).balanceOf(address(this));
uint256 balance1 = IERC20(_token1).balanceOf(address(this));
uint256 liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(
amount0 > 0 && amount1 > 0,
"Pair: INSUFFICIENT_LIQUIDITY_BURNED"
);
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external override nonReentrant {
require(
amount0Out > 0 || amount1Out > 0,
"Pair: INSUFFICIENT_OUTPUT_AMOUNT"
);
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
require(
amount0Out < _reserve0 && amount1Out < _reserve1,
"Pair: INSUFFICIENT_LIQUIDITY"
);
uint256 balance0;
uint256 balance1;
{
// scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, "Pair: INVALID_TO");
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0)
ITetherswapCallee(to).TetherswapCall(
msg.sender,
amount0Out,
amount1Out,
data
);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
if (ITetherswapFactory(factory).maxSlippagePercent() > 0) {
uint256 currentPrice = balance0.mul(1e18) / balance1;
if (priceAtLastSlippageBlocks == 0) {
priceAtLastSlippageBlocks = currentPrice;
lastSlippageBlocks = block.number;
} else {
bool resetSlippage =
lastSlippageBlocks.add(
ITetherswapFactory(factory).maxSlippageBlocks()
) < block.number;
uint256 lastPrice =
resetSlippage
? lastSwapPrice
: priceAtLastSlippageBlocks;
require(
currentPrice >=
lastPrice.mul(
uint256(100).sub(
ITetherswapFactory(factory)
.maxSlippagePercent()
)
) /
100 &&
currentPrice <=
lastPrice.mul(
uint256(100).add(
ITetherswapFactory(factory)
.maxSlippagePercent()
)
) /
100,
"Pair: SlipLock"
);
if (resetSlippage) {
priceAtLastSlippageBlocks = currentPrice;
lastSlippageBlocks = block.number;
}
}
lastSwapPrice = currentPrice;
}
}
uint256 amount0In =
balance0 > _reserve0 - amount0Out
? balance0 - (_reserve0 - amount0Out)
: 0;
uint256 amount1In =
balance1 > _reserve1 - amount1Out
? balance1 - (_reserve1 - amount1Out)
: 0;
require(
amount0In > 0 || amount1In > 0,
"Pair: INSUFFICIENT_INPUT_AMOUNT"
);
{
// scope for balance{0,1}Adjusted, avoids stack too deep errors
uint256 balance0Adjusted =
balance0.mul(1e6).sub(amount0In.mul(tradingFeePercent));
uint256 balance1Adjusted =
balance1.mul(1e6).sub(amount1In.mul(tradingFeePercent));
require(
balance0Adjusted.mul(balance1Adjusted) >=
uint256(_reserve0).mul(_reserve1).mul(1e6**2),
"Pair: K"
);
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external override nonReentrant {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(
_token0,
to,
IERC20(_token0).balanceOf(address(this)).sub(reserve0)
);
_safeTransfer(
_token1,
to,
IERC20(_token1).balanceOf(address(this)).sub(reserve1)
);
}
// force reserves to match balances
function sync() external override nonReentrant {
_update(
IERC20(token0).balanceOf(address(this)),
IERC20(token1).balanceOf(address(this)),
reserve0,
reserve1
);
}
function _setTradingFeePercent(uint256 _tradingFeePercent) private {
// max 1%
require(
_tradingFeePercent <= 10000,
"Pair: INVALID_TRADING_FEE_PERCENT"
);
tradingFeePercent = _tradingFeePercent;
}
function setTradingFeePercent(uint256 _tradingFeePercent)
external
override
onlyGovernance
{
_setTradingFeePercent(_tradingFeePercent);
}
}
// 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);
}
pragma solidity 0.6.6;
// a library for performing various math operations
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
pragma solidity 0.6.6;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
pragma solidity 0.6.6;
interface ITetherswapCallee {
function TetherswapCall(
address sender,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
}
pragma solidity 0.6.6;
import "./ITetherswapERC20.sol";
interface ITetherswapPair is ITetherswapERC20 {
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Lock(
address indexed sender,
uint256 lockupPeriod,
uint256 liquidityLockupAmount
);
event Unlock(address indexed sender, uint256 liquidityUnlocked);
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 addressToLockupExpiry(address) external view returns (uint256);
function addressToLockupAmount(address) external view 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 tradingFeePercent() external view returns (uint256);
function lastSlippageBlocks() external view returns (uint256);
function priceAtLastSlippageBlocks() external view returns (uint256);
function lastSwapPrice() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function lock(uint256 lockupPeriod, uint256 liquidityLockupAmount) external;
function unlock() external;
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 setTradingFeePercent(uint256 _tradingFeePercent) external;
// functions only callable by TetherswapFactory
function initialize(
address _token0,
address _token1,
uint256 _tradingFeePercent
) external;
function listingLock(
address lister,
uint256 lockupPeriod,
uint256 liquidityLockupAmount
) external;
}
pragma solidity 0.6.6;
interface ITetherswapERC20 {
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;
} | babylonian method (https:en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) | function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
z = 1;
}
| 12,045,100 | [
1,
70,
24383,
9379,
2779,
707,
261,
4528,
30,
275,
18,
11999,
13744,
18,
3341,
19,
13044,
19,
4712,
67,
792,
67,
13406,
310,
67,
19719,
67,
22078,
38,
24383,
9379,
2779,
67,
2039,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
5700,
12,
11890,
5034,
677,
13,
2713,
16618,
1135,
261,
11890,
5034,
998,
13,
288,
203,
3639,
309,
261,
93,
405,
890,
13,
288,
203,
5411,
998,
273,
677,
31,
203,
5411,
2254,
5034,
619,
273,
677,
342,
576,
397,
404,
31,
203,
5411,
1323,
261,
92,
411,
998,
13,
288,
203,
7734,
998,
273,
619,
31,
203,
7734,
619,
273,
261,
93,
342,
619,
397,
619,
13,
342,
576,
31,
203,
5411,
289,
203,
5411,
998,
273,
404,
31,
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
] |
pragma solidity ^0.5.12;
import "./InterchainAccount.sol";
contract InterchainAccountRouter {
event InterchainAccountCreated(address);
struct InterchainAccountTx {
address from;
address to;
uint256 value;
bytes data;
}
mapping (address => bool) interchainAccounts;
// If RegisterIBCAccountPacket is delivered from IBC, `createAccount` will create new interchain account and returns its address to sending chain.
function createAccount() public returns (address) {
InterchainAccount iaContract = new InterchainAccount();
interchainAccounts[address(iaContract)] = true;
emit InterchainAccountCreated(address(iaContract));
return address(iaContract);
}
// TODO: using salt by CREATE2 opcode.
// generateAddress(identifier: Identifier, salt: Uint8Array): Uint8Array
// Mockup for receiving run tx packet.
function receiveRunTxPacket(bytes memory txBytes) public {
InterchainAccountTx memory interchainAccountTx = deserializeTx(txBytes);
authenticateTx(interchainAccountTx);
require(runTx(interchainAccountTx));
}
function deserializeTx(bytes memory txBytes) private pure returns (InterchainAccountTx memory) {
address from;
address to;
uint256 value;
bytes memory data;
(from, to, value, data) = abi.decode(txBytes, (address, address, uint256, bytes));
InterchainAccountTx memory interchainAccountTx;
interchainAccountTx.from = from;
interchainAccountTx.to = to;
interchainAccountTx.value = value;
interchainAccountTx.data = data;
return interchainAccountTx;
}
function authenticateTx(InterchainAccountTx memory interchainAccountTx) private view returns (bool) {
require(interchainAccounts[interchainAccountTx.from]);
return true;
}
function runTx(InterchainAccountTx memory interchainAccountTx) private returns (bool) {
(bool success, bytes memory _) = InterchainAccount(interchainAccountTx.from).runTx(interchainAccountTx.to, interchainAccountTx.value, interchainAccountTx.data);
return success;
}
}
| Mockup for receiving run tx packet. | function receiveRunTxPacket(bytes memory txBytes) public {
InterchainAccountTx memory interchainAccountTx = deserializeTx(txBytes);
authenticateTx(interchainAccountTx);
require(runTx(interchainAccountTx));
}
| 12,557,651 | [
1,
9865,
416,
364,
15847,
1086,
2229,
4414,
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
] | [
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,
225,
445,
6798,
1997,
4188,
6667,
12,
3890,
3778,
2229,
2160,
13,
1071,
288,
203,
565,
5294,
5639,
3032,
4188,
3778,
1554,
5639,
3032,
4188,
273,
7673,
4188,
12,
978,
2160,
1769,
203,
565,
8929,
4188,
12,
2761,
5639,
3032,
4188,
1769,
203,
565,
2583,
12,
2681,
4188,
12,
2761,
5639,
3032,
4188,
10019,
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
] |
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
library PlasmaData {
struct Account {
address owner;
uint pubKeyX;
uint pubKeyY;
}
struct Request {
uint accumulatedHash;
uint timestamp;
}
struct Withdrawal {
uint accountId;
uint amount;
}
enum BlockType {
TRANSFER,
DEPOSIT,
ONCHAIN_WITHDRAWAL,
OFFCHAIN_WITHDRAWAL
}
enum BlockState {
COMMITTED, // = 0
VERIFIED // = 1
}
struct BlockData {
uint merkleRootBefore;
uint merkleRootAfter;
uint startIdx;
uint count;
uint inputStartingHash;
uint inputEndingHash;
uint withdrawalsLength;
mapping(uint => Withdrawal) withdrawals;
}
struct Block {
BlockState state;
BlockType blockType;
uint numWithdrawalsDistributed;
BlockData blockData;
}
struct State {
Block[] blocks;
Account[] accounts;
Request[] depositChain;
Request[] withdrawalChain;
uint numDepositRequestsCommitted;
uint numWithdrawalRequestsCommitted;
mapping (address => uint) ownerToAccountId;
mapping (address => uint) tokenToTokenId;
mapping (address => uint) tokenBalances;
uint numBlocksFinalized;
}
function blockDataToBytes(PlasmaData.BlockData memory data)
internal
pure
returns (bytes memory)
{
bytes memory dataBytes = abi.encode(
data.merkleRootBefore,
data.merkleRootAfter,
data.startIdx,
data.count,
data.inputStartingHash,
data.inputEndingHash);
return dataBytes;
}
// Constants getters --------------------------------------------
function BLOCK_SIZE() internal pure returns (uint) { return 8; }
function SNARK_SCALAR_FIELD() internal pure returns (uint) {
// This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196.
return 21888242871839275222246405745257275088548364400416034343698204186575808495617;
}
function MAX_NUM_ACCOUNTS() internal pure returns (uint) { return 2 ** 20 - 1; }
function MIN_GAS_TO_DISTRIBUTE_WITHDRAWALS() internal pure returns (uint) { return 150000; }
function GAS_LIMIT_SEND_ETHER() internal pure returns (uint) { return 30000; }
}
| This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196. | function SNARK_SCALAR_FIELD() internal pure returns (uint) {
return 21888242871839275222246405745257275088548364400416034343698204186575808495617;
}
| 5,386,010 | [
1,
2503,
353,
326,
17014,
1300,
716,
353,
1399,
364,
326,
3770,
67,
13392,
10392,
415,
549,
21507,
8882,
16,
2621,
512,
2579,
17,
28644,
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
] | [
1,
1,
1,
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
] | [
1,
565,
445,
14204,
9584,
67,
2312,
1013,
985,
67,
6776,
1435,
2713,
16618,
1135,
261,
11890,
13,
288,
203,
3639,
327,
576,
2643,
5482,
3247,
6030,
27,
2643,
5520,
5324,
25,
3787,
23622,
1105,
6260,
5608,
25,
2947,
27,
5324,
3361,
5482,
6564,
10261,
1105,
16010,
24,
2313,
4630,
24,
5026,
5718,
10689,
21573,
2643,
9222,
5877,
3672,
5193,
29,
4313,
4033,
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
] |
./partial_match/1/0xfF13851Aa596359c9ab50E34AAd3e98E8590e8ec/sources/Contract.sol | ===== Whitelisting ===== | function isAddressWhitelisted(bytes32[] memory proof, address _address) internal view returns (bool) {
return proof.verify(presaleMerkleRoot, keccak256(abi.encodePacked(_address)));
}
| 15,946,060 | [
1,
894,
33,
3497,
7523,
310,
422,
12275,
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,
353,
1887,
18927,
329,
12,
3890,
1578,
8526,
3778,
14601,
16,
1758,
389,
2867,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
14601,
18,
8705,
12,
12202,
5349,
8478,
15609,
2375,
16,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
2867,
3719,
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
] |
// Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
// pragma solidity ^0.6.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");
}
}
}
// Dependency file: contracts/interfaces/ISetValuer.sol
/*
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.
*/
// pragma solidity 0.6.10;
// import { ISetToken } from "../interfaces/ISetToken.sol";
interface ISetValuer {
function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256);
}
// Dependency file: contracts/interfaces/IPriceOracle.sol
/*
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.
*/
// pragma solidity 0.6.10;
/**
* @title IPriceOracle
* @author Set Protocol
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
}
// Dependency file: contracts/interfaces/IIntegrationRegistry.sol
/*
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.
*/
// 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);
}
// Dependency file: contracts/interfaces/IModule.sol
/*
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.
*/
// pragma solidity 0.6.10;
/**
* @title IModule
* @author Set Protocol
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
// Dependency file: contracts/lib/ExplicitERC20.sol
/*
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.
*/
// pragma solidity 0.6.10;
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title ExplicitERC20
* @author Set Protocol
*
* 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"
);
}
}
}
// Dependency 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);
}
}
}
}
// Dependency 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;
}
}
// Dependency file: contracts/protocol/lib/ResourceIdentifier.sol
/*
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.
*/
// pragma solidity 0.6.10;
// import { IController } from "../../interfaces/IController.sol";
// import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol";
// import { IPriceOracle } from "../../interfaces/IPriceOracle.sol";
// import { ISetValuer } from "../../interfaces/ISetValuer.sol";
/**
* @title ResourceIdentifier
* @author Set Protocol
*
* 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;
// SetValuer resource will always be resource ID 2 in the system
uint256 constant internal SET_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 Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller
*/
function getSetValuer(IController _controller) internal view returns (ISetValuer) {
return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID));
}
}
// Dependency file: contracts/lib/PreciseUnitMath.sol
/*
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.
*/
// pragma solidity 0.6.10;
// pragma experimental ABIEncoderV2;
// import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
// import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*/
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);
}
}
// Dependency file: contracts/protocol/lib/Position.sol
/*
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.
*/
// pragma solidity 0.6.10;
// pragma experimental "ABIEncoderV2";
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
// import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
// import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
// import { ISetToken } from "../../interfaces/ISetToken.sol";
// import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title Position
* @author Set Protocol
*
* Collection of helper functions for handling and updating SetToken Positions
*/
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 SetToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the SetToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the SetToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the SetToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ISetToken _setToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the SetToken. 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 _setToken Address of SetToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_setToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_setToken, _component)) {
_setToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_setToken, _component)) {
_setToken.removeComponent(_component);
}
}
_setToken.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
* 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 _setToken SetToken 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(
ISetToken _setToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (!_setToken.isComponent(_component)) {
_setToken.addComponent(_component);
addExternalPosition(_setToken, _component, _module, _newUnit, _data);
} else if (!_setToken.isExternalPositionModule(_component, _module)) {
addExternalPosition(_setToken, _component, _module, _newUnit, _data);
} else if (_newUnit != 0) {
_setToken.editExternalPositionUnit(_component, _module, _newUnit);
} else {
// If no default or external position remaining then remove component from components array
if (_setToken.getDefaultPositionRealUnit(_component) == 0 && _setToken.getExternalPositionModules(_component).length == 1) {
_setToken.removeComponent(_component);
}
_setToken.removeExternalPositionModule(_component, _module);
}
}
/**
* Add a new external position from a previously untracked module.
*
* @param _setToken SetToken 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 addExternalPosition(
ISetToken _setToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
_setToken.addExternalPositionModule(_component, _module);
_setToken.editExternalPositionUnit(_component, _module, _newUnit);
_setToken.editExternalPositionData(_component, _module, _data);
}
/**
* Get total notional amount of Default position
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _setTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_setTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) {
int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component);
return _setToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @param _setTotalSupply Current SetToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ISetToken _setToken,
address _component,
uint256 _setTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken));
uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit = calculateDefaultEditPositionUnit(
_setTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
editDefaultPosition(_setToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _setTokenSupply Supply of SetToken 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 SetToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _setTokenSupply,
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
if (_preTotalNotional >= _postTotalNotional) {
uint256 unitsToSub = _preTotalNotional.sub(_postTotalNotional).preciseDivCeil(_setTokenSupply);
return _prePositionUnit.sub(unitsToSub);
} else {
// Else subtract post action total notional from pre action total notional and calculate new position units
uint256 unitsToAdd = _postTotalNotional.sub(_preTotalNotional).preciseDiv(_setTokenSupply);
return _prePositionUnit.add(unitsToAdd);
}
}
}
// Dependency file: contracts/protocol/lib/ModuleBase.sol
/*
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.
*/
// pragma solidity 0.6.10;
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol";
// import { IController } from "../../interfaces/IController.sol";
// import { IModule } from "../../interfaces/IModule.sol";
// import { ISetToken } from "../../interfaces/ISetToken.sol";
// import { Invoke } from "./Invoke.sol";
// import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
// import { ResourceIdentifier } from "./ResourceIdentifier.sol";
/**
* @title ModuleBase
* @author Set Protocol
*
* Abstract class that houses common Module-related state and functions.
*/
abstract contract ModuleBase is IModule {
using PreciseUnitMath for uint256;
using Invoke for ISetToken;
using ResourceIdentifier for IController;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidSet(ISetToken _setToken) {
require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager");
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
_;
}
modifier onlySetManager(ISetToken _setToken, address _caller) {
require(isSetManager(_setToken, _caller), "Must be the SetToken manager");
_;
}
modifier onlyValidAndInitializedSet(ISetToken _setToken) {
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
_;
}
/**
* Throws if the sender is not a SetToken's module or module not enabled
*/
modifier onlyModule(ISetToken _setToken) {
require(
_setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the SetToken is valid
*/
modifier onlyValidAndPendingSet(ISetToken _setToken) {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
_;
}
/* ============ 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 _setToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the SetToken
*/
function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) {
return _setToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the SetToken's manager
*/
function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) {
return _setToken.manager() == _toCheck;
}
/**
* Returns true if SetToken must be enabled on the controller
* and module is registered on the SetToken
*/
function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) {
return controller.isSet(address(_setToken)) &&
_setToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// pragma solidity ^0.6.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);
}
// Dependency file: contracts/interfaces/external/IWETH.sol
/*
Copyright 2018 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.
*/
// pragma solidity 0.6.10;
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title IWETH
* @author Set Protocol
*
* 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;
}
// Dependency file: contracts/interfaces/ISetToken.sol
/*
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.
*/
// pragma solidity 0.6.10;
// pragma experimental "ABIEncoderV2";
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken 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 SetToken
* @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);
}
// Dependency file: contracts/protocol/lib/Invoke.sol
/*
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.
*/
// pragma solidity 0.6.10;
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
// import { ISetToken } from "../../interfaces/ISetToken.sol";
/**
* @title Invoke
* @author Set Protocol
*
* A collection of common utility functions for interacting with the SetToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the SetToken to set approvals of the ERC20 token to a spender.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the SetToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ISetToken _setToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_setToken.invoke(_token, 0, callData);
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_setToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
* The new SetToken balance must equal the existing balance less the quantity transferred
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the SetToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken));
Invoke.invokeTransfer(_setToken, _token, _to, _quantity);
// Get new balance of transferred token for SetToken
uint256 newBalance = IERC20(_token).balanceOf(address(_setToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the SetToken to unwrap the passed quantity of WETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_setToken.invoke(_weth, 0, callData);
}
/**
* Instructs the SetToken to wrap the passed quantity of ETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_setToken.invoke(_weth, _quantity, callData);
}
}
// Dependency file: contracts/interfaces/INAVIssuanceHook.sol
/*
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.
*/
// pragma solidity 0.6.10;
// import { ISetToken } from "./ISetToken.sol";
interface INAVIssuanceHook {
function invokePreIssueHook(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
address _sender,
address _to
)
external;
function invokePreRedeemHook(
ISetToken _setToken,
uint256 _redeemQuantity,
address _sender,
address _to
)
external;
}
// Dependency file: contracts/interfaces/IController.sol
/*
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.
*/
// pragma solidity 0.6.10;
interface IController {
function addSet(address _setToken) 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 isSet(address _setToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
// Dependency file: contracts/lib/AddressArrayUtils.sol
/*
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.
*/
// pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* 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;
}
}
/**
* 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]);
}
}
// Dependency file: @openzeppelin/contracts/math/SignedSafeMath.sol
// pragma solidity ^0.6.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;
}
}
// Dependency 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;
}
}
// Dependency file: @openzeppelin/contracts/utils/SafeCast.sol
// pragma solidity ^0.6.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);
}
}
// Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol
// pragma solidity ^0.6.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].
*/
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;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/ERC20.sol
// pragma solidity ^0.6.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) 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 { }
}
/*
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.
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
// import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
// import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
// import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
// import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
// import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
// import { IController } from "../../interfaces/IController.sol";
// import { INAVIssuanceHook } from "../../interfaces/INAVIssuanceHook.sol";
// import { Invoke } from "../lib/Invoke.sol";
// import { ISetToken } from "../../interfaces/ISetToken.sol";
// import { IWETH } from "../../interfaces/external/IWETH.sol";
// import { ModuleBase } from "../lib/ModuleBase.sol";
// import { Position } from "../lib/Position.sol";
// import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
// import { ResourceIdentifier } from "../lib/ResourceIdentifier.sol";
/**
* @title NavIssuanceModule
* @author Set Protocol
*
* Module that enables issuance and redemption with any valid ERC20 token or ETH if allowed by the manager. Sender receives
* a proportional amount of SetTokens on issuance or ERC20 token on redemption based on the calculated net asset value using
* oracle prices. Manager is able to enforce a premium / discount on issuance / redemption to avoid arbitrage and front
* running when relying on oracle prices. Managers can charge a fee (denominated in reserve asset).
*/
contract NavIssuanceModule is ModuleBase, ReentrancyGuard {
using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using PreciseUnitMath for int256;
using ResourceIdentifier for IController;
using SafeMath for uint256;
using SafeCast for int256;
using SafeCast for uint256;
using SignedSafeMath for int256;
/* ============ Events ============ */
event SetTokenNAVIssued(
address indexed _setToken,
address _issuer,
address _to,
address _reserveAsset,
address _hookContract,
uint256 _setTokenQuantity,
uint256 _managerFee,
uint256 _premium
);
event SetTokenNAVRedeemed(
address indexed _setToken,
address _redeemer,
address _to,
address _reserveAsset,
address _hookContract,
uint256 _setTokenQuantity,
uint256 _managerFee,
uint256 _premium
);
/* ============ Structs ============ */
struct NAVIssuanceSettings {
INAVIssuanceHook managerIssuanceHook; // Issuance hook configurations
INAVIssuanceHook managerRedemptionHook; // Redemption hook configurations
address[] reserveAssets; // Allowed reserve assets - Must have a price enabled with the price oracle
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 premiumPercentage; // Premium percentage (0.01% = 1e14, 1% = 1e16). This premium is a buffer around oracle
// prices paid by user to the SetToken, which prevents arbitrage and oracle front running
uint256 maxPremiumPercentage; // Maximum premium percentage manager is allowed to set (configured by manager)
uint256 minSetTokenSupply; // Minimum SetToken supply required for issuance and redemption
// to prevent dramatic inflationary changes to the SetToken's position multiplier
}
struct ActionInfo {
uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity
// During redeem, represents post-premium value
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 SetToken
// When redeeming, quantity of reserve asset sent to redeemer
uint256 setTokenQuantity; // When issuing, quantity of SetTokens minted to mintee
// When redeeming, quantity of SetToken redeemed
uint256 previousSetTokenSupply; // SetToken supply prior to issue/redeem action
uint256 newSetTokenSupply; // SetToken supply after issue/redeem action
int256 newPositionMultiplier; // SetToken position multiplier after issue/redeem
uint256 newReservePositionUnit; // SetToken reserve asset position unit after issue/redeem
}
/* ============ State Variables ============ */
// Wrapped ETH address
IWETH public weth;
// Mapping of SetToken to NAV issuance settings struct
mapping(ISetToken => NAVIssuanceSettings) public navIssuanceSettings;
// Mapping to efficiently check a SetToken's reserve asset validity
// SetToken => reserveAsset => isReserveAsset
mapping(ISetToken => mapping(address => bool)) public isReserveAsset;
/* ============ Constants ============ */
// 0 index stores the manager fee percentage charged in issue (denominated in reserve asset)
uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0;
// 1 index stores the manager fee percentage charged in redeem
uint256 constant internal MANAGER_REDEEM_FEE_INDEX = 1;
// 0 index stores the manager revenue share protocol fee % charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0;
// 1 index stores the manager revenue share protocol fee % charged in the redeem function
uint256 constant internal PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX = 1;
// 2 index stores the direct protocol fee % charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2;
// 3 index stores the direct protocol fee % charged in the redeem function
uint256 constant internal PROTOCOL_REDEEM_DIRECT_FEE_INDEX = 3;
/* ============ Constructor ============ */
/**
* @param _controller Address of controller contract
* @param _weth Address of wrapped eth
*/
constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) {
weth = _weth;
}
/* ============ External Functions ============ */
/**
* Deposits the allowed reserve asset into the SetToken and mints the appropriate % of Net Asset Value of the SetToken
* to the specified _to address.
*
* @param _setToken Instance of the SetToken contract
* @param _reserveAsset Address of the reserve asset to issue with
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
* @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance
* @param _to Address to mint SetToken to
*/
function issue(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
uint256 _minSetTokenReceiveQuantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, _reserveAsset, _reserveAssetQuantity);
_callPreIssueHooks(_setToken, _reserveAsset, _reserveAssetQuantity, msg.sender, _to);
ActionInfo memory issueInfo = _getIssuanceInfo(_setToken, _reserveAsset, _reserveAssetQuantity);
_validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo);
_transferCollateralAndHandleFees(_setToken, IERC20(_reserveAsset), issueInfo);
_handleIssueStateUpdates(_setToken, _reserveAsset, _to, issueInfo);
}
/**
* Wraps ETH and deposits WETH if allowed into the SetToken and mints the appropriate % of Net Asset Value of the SetToken
* to the specified _to address.
*
* @param _setToken Instance of the SetToken contract
* @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance
* @param _to Address to mint SetToken to
*/
function issueWithEther(
ISetToken _setToken,
uint256 _minSetTokenReceiveQuantity,
address _to
)
external
payable
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
weth.deposit{ value: msg.value }();
_validateCommon(_setToken, address(weth), msg.value);
_callPreIssueHooks(_setToken, address(weth), msg.value, msg.sender, _to);
ActionInfo memory issueInfo = _getIssuanceInfo(_setToken, address(weth), msg.value);
_validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo);
_transferWETHAndHandleFees(_setToken, issueInfo);
_handleIssueStateUpdates(_setToken, address(weth), _to, issueInfo);
}
/**
* Redeems a SetToken into a valid reserve asset representing the appropriate % of Net Asset Value of the SetToken
* to the specified _to address. Only valid if there are available reserve units on the SetToken.
*
* @param _setToken Instance of the SetToken contract
* @param _reserveAsset Address of the reserve asset to redeem with
* @param _setTokenQuantity Quantity of SetTokens to redeem
* @param _minReserveReceiveQuantity Min quantity of reserve asset to receive
* @param _to Address to redeem reserve asset to
*/
function redeem(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity,
uint256 _minReserveReceiveQuantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, _reserveAsset, _setTokenQuantity);
_callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to);
ActionInfo memory redeemInfo = _getRedemptionInfo(_setToken, _reserveAsset, _setTokenQuantity);
_validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo);
_setToken.burn(msg.sender, _setTokenQuantity);
// Instruct the SetToken to transfer the reserve asset back to the user
_setToken.strictInvokeTransfer(
_reserveAsset,
_to,
redeemInfo.netFlowQuantity
);
_handleRedemptionFees(_setToken, _reserveAsset, redeemInfo);
_handleRedeemStateUpdates(_setToken, _reserveAsset, _to, redeemInfo);
}
/**
* Redeems a SetToken into Ether (if WETH is valid) representing the appropriate % of Net Asset Value of the SetToken
* to the specified _to address. Only valid if there are available WETH units on the SetToken.
*
* @param _setToken Instance of the SetToken contract
* @param _setTokenQuantity Quantity of SetTokens to redeem
* @param _minReserveReceiveQuantity Min quantity of reserve asset to receive
* @param _to Address to redeem reserve asset to
*/
function redeemIntoEther(
ISetToken _setToken,
uint256 _setTokenQuantity,
uint256 _minReserveReceiveQuantity,
address payable _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, address(weth), _setTokenQuantity);
_callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to);
ActionInfo memory redeemInfo = _getRedemptionInfo(_setToken, address(weth), _setTokenQuantity);
_validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo);
_setToken.burn(msg.sender, _setTokenQuantity);
// Instruct the SetToken to transfer WETH from SetToken to module
_setToken.strictInvokeTransfer(
address(weth),
address(this),
redeemInfo.netFlowQuantity
);
weth.withdraw(redeemInfo.netFlowQuantity);
_to.transfer(redeemInfo.netFlowQuantity);
_handleRedemptionFees(_setToken, address(weth), redeemInfo);
_handleRedeemStateUpdates(_setToken, address(weth), _to, redeemInfo);
}
/**
* SET MANAGER ONLY. Add an allowed reserve asset
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset to add
*/
function addReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) {
require(!isReserveAsset[_setToken][_reserveAsset], "Reserve asset already exists");
navIssuanceSettings[_setToken].reserveAssets.push(_reserveAsset);
isReserveAsset[_setToken][_reserveAsset] = true;
}
/**
* SET MANAGER ONLY. Remove a reserve asset
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset to remove
*/
function removeReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) {
require(isReserveAsset[_setToken][_reserveAsset], "Reserve asset does not exist");
navIssuanceSettings[_setToken].reserveAssets = navIssuanceSettings[_setToken].reserveAssets.remove(_reserveAsset);
delete isReserveAsset[_setToken][_reserveAsset];
}
/**
* SET MANAGER ONLY. Edit the premium percentage
*
* @param _setToken Instance of the SetToken
* @param _premiumPercentage Premium percentage in 10e16 (e.g. 10e16 = 1%)
*/
function editPremium(ISetToken _setToken, uint256 _premiumPercentage) external onlyManagerAndValidSet(_setToken) {
require(_premiumPercentage < navIssuanceSettings[_setToken].maxPremiumPercentage, "Premium must be less than maximum allowed");
navIssuanceSettings[_setToken].premiumPercentage = _premiumPercentage;
}
/**
* SET MANAGER ONLY. Edit manager fee
*
* @param _setToken Instance of the SetToken
* @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(
ISetToken _setToken,
uint256 _managerFeePercentage,
uint256 _managerFeeIndex
)
external
onlyManagerAndValidSet(_setToken)
{
require(_managerFeePercentage < navIssuanceSettings[_setToken].maxManagerFee, "Manager fee must be less than maximum allowed");
navIssuanceSettings[_setToken].managerFees[_managerFeeIndex] = _managerFeePercentage;
}
/**
* SET MANAGER ONLY. Edit the manager fee recipient
*
* @param _setToken Instance of the SetToken
* @param _managerFeeRecipient Manager fee recipient
*/
function editFeeRecipient(ISetToken _setToken, address _managerFeeRecipient) external onlyManagerAndValidSet(_setToken) {
require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address");
navIssuanceSettings[_setToken].feeRecipient = _managerFeeRecipient;
}
/**
* SET MANAGER ONLY. Initializes this module to the SetToken with hooks, allowed reserve assets,
* fees and issuance premium. Only callable by the SetToken's manager. Hook addresses are optional.
* Address(0) means that no hook will be called.
*
* @param _setToken Instance of the SetToken to issue
* @param _navIssuanceSettings NAVIssuanceSettings struct defining parameters
*/
function initialize(
ISetToken _setToken,
NAVIssuanceSettings memory _navIssuanceSettings
)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_navIssuanceSettings.reserveAssets.length > 0, "Reserve assets must be greater than 0");
require(_navIssuanceSettings.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%");
require(_navIssuanceSettings.maxPremiumPercentage < PreciseUnitMath.preciseUnit(), "Max premium percentage must be less than 100%");
require(_navIssuanceSettings.managerFees[0] <= _navIssuanceSettings.maxManagerFee, "Manager issue fee must be less than max");
require(_navIssuanceSettings.managerFees[1] <= _navIssuanceSettings.maxManagerFee, "Manager redeem fee must be less than max");
require(_navIssuanceSettings.premiumPercentage <= _navIssuanceSettings.maxPremiumPercentage, "Premium must be less than max");
require(_navIssuanceSettings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
// Initial mint of Set cannot use NAVIssuance since minSetTokenSupply must be > 0
require(_navIssuanceSettings.minSetTokenSupply > 0, "Min SetToken supply must be greater than 0");
for (uint256 i = 0; i < _navIssuanceSettings.reserveAssets.length; i++) {
isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]] = true;
}
navIssuanceSettings[_setToken] = _navIssuanceSettings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Issuance settings and
* reserve asset states are deleted.
*/
function removeModule() external override {
ISetToken setToken = ISetToken(msg.sender);
for (uint256 i = 0; i < navIssuanceSettings[setToken].reserveAssets.length; i++) {
delete isReserveAsset[setToken][navIssuanceSettings[setToken].reserveAssets[i]];
}
delete navIssuanceSettings[setToken];
}
receive() external payable {}
/* ============ External Getter Functions ============ */
function getReserveAssets(ISetToken _setToken) external view returns (address[] memory) {
return navIssuanceSettings[_setToken].reserveAssets;
}
function isValidReserveAsset(ISetToken _setToken, address _reserveAsset) external view returns (bool) {
return isReserveAsset[_setToken][_reserveAsset];
}
function getIssuePremium(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (uint256)
{
return _getIssuePremium(_setToken, _reserveAsset, _reserveAssetQuantity);
}
function getRedeemPremium(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (uint256)
{
return _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity);
}
function getManagerFee(ISetToken _setToken, uint256 _managerFeeIndex) external view returns (uint256) {
return navIssuanceSettings[_setToken].managerFees[_managerFeeIndex];
}
/**
* Get the expected SetTokens minted to recipient on issuance
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
*
* @return uint256 Expected SetTokens to be minted to recipient
*/
function getExpectedSetTokenIssueQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (uint256)
{
(,, uint256 netReserveFlow) = _getFees(
_setToken,
_reserveAssetQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
uint256 setTotalSupply = _setToken.totalSupply();
return _getSetTokenMintQuantity(
_setToken,
_reserveAsset,
netReserveFlow,
setTotalSupply
);
}
/**
* Get the expected reserve asset to be redeemed
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _setTokenQuantity Quantity of SetTokens to redeem
*
* @return uint256 Expected reserve asset quantity redeemed
*/
function getExpectedReserveRedeemQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (uint256)
{
uint256 preFeeReserveQuantity = _getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(,, uint256 netReserveFlows) = _getFees(
_setToken,
preFeeReserveQuantity,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
return netReserveFlows;
}
/**
* Checks if issue is valid
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
*
* @return bool Returns true if issue is valid
*/
function isIssueValid(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (bool)
{
uint256 setTotalSupply = _setToken.totalSupply();
if (
_reserveAssetQuantity == 0
|| !isReserveAsset[_setToken][_reserveAsset]
|| setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply
) {
return false;
}
return true;
}
/**
* Checks if redeem is valid
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _setTokenQuantity Quantity of SetTokens to redeem
*
* @return bool Returns true if redeem is valid
*/
function isRedeemValid(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (bool)
{
uint256 setTotalSupply = _setToken.totalSupply();
if (
_setTokenQuantity == 0
|| !isReserveAsset[_setToken][_reserveAsset]
|| setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply.add(_setTokenQuantity)
) {
return false;
}
uint256 totalRedeemValue =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(,, uint256 expectedRedeemQuantity) = _getFees(
_setToken,
totalRedeemValue,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
if (existingUnit.preciseMul(setTotalSupply) < expectedRedeemQuantity) {
return false;
}
return true;
}
/* ============ Internal Functions ============ */
function _validateCommon(ISetToken _setToken, address _reserveAsset, uint256 _quantity) internal view {
require(_quantity > 0, "Quantity must be > 0");
require(isReserveAsset[_setToken][_reserveAsset], "Must be valid reserve asset");
}
function _validateIssuanceInfo(ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, 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 SetToken supply is 0
require(
_issueInfo.previousSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply,
"Supply must be greater than minimum to enable issuance"
);
require(_issueInfo.setTokenQuantity >= _minSetTokenReceiveQuantity, "Must be greater than min SetToken");
}
function _validateRedemptionInfo(
ISetToken _setToken,
uint256 _minReserveReceiveQuantity,
uint256 _setTokenQuantity,
ActionInfo memory _redeemInfo
)
internal
view
{
// Check that new supply is more than min supply needed for redemption
// Note: A min supply amount is needed to avoid division by 0 when redeeming SetToken to 0
require(
_redeemInfo.newSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply,
"Supply must be greater than minimum to enable redemption"
);
require(_redeemInfo.netFlowQuantity >= _minReserveReceiveQuantity, "Must be greater than min receive reserve quantity");
}
function _getIssuanceInfo(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory issueInfo;
issueInfo.previousSetTokenSupply = _setToken.totalSupply();
issueInfo.preFeeReserveQuantity = _reserveAssetQuantity;
(issueInfo.protocolFees, issueInfo.managerFee, issueInfo.netFlowQuantity) = _getFees(
_setToken,
issueInfo.preFeeReserveQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
issueInfo.setTokenQuantity = _getSetTokenMintQuantity(
_setToken,
_reserveAsset,
issueInfo.netFlowQuantity,
issueInfo.previousSetTokenSupply
);
(issueInfo.newSetTokenSupply, issueInfo.newPositionMultiplier) = _getIssuePositionMultiplier(_setToken, issueInfo);
issueInfo.newReservePositionUnit = _getIssuePositionUnit(_setToken, _reserveAsset, issueInfo);
return issueInfo;
}
function _getRedemptionInfo(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory redeemInfo;
redeemInfo.setTokenQuantity = _setTokenQuantity;
redeemInfo.preFeeReserveQuantity =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(redeemInfo.protocolFees, redeemInfo.managerFee, redeemInfo.netFlowQuantity) = _getFees(
_setToken,
redeemInfo.preFeeReserveQuantity,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
redeemInfo.previousSetTokenSupply = _setToken.totalSupply();
(redeemInfo.newSetTokenSupply, redeemInfo.newPositionMultiplier) = _getRedeemPositionMultiplier(_setToken, _setTokenQuantity, redeemInfo);
redeemInfo.newReservePositionUnit = _getRedeemPositionUnit(_setToken, _reserveAsset, redeemInfo);
return redeemInfo;
}
/**
* Transfer reserve asset from user to SetToken and fees from user to appropriate fee recipients
**/
function _transferCollateralAndHandleFees(ISetToken _setToken, IERC20 _reserveAsset, ActionInfo memory _issueInfo) internal {
transferFrom(_reserveAsset, msg.sender, address(_setToken), _issueInfo.netFlowQuantity);
if (_issueInfo.protocolFees > 0) {
transferFrom(_reserveAsset, msg.sender, controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
transferFrom(_reserveAsset, msg.sender, navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee);
}
}
/**
* Transfer WETH from module to SetToken and fees from module to appropriate fee recipients
**/
function _transferWETHAndHandleFees(ISetToken _setToken, ActionInfo memory _issueInfo) internal {
weth.transfer(address(_setToken), _issueInfo.netFlowQuantity);
if (_issueInfo.protocolFees > 0) {
weth.transfer(controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
weth.transfer(navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee);
}
}
function _handleIssueStateUpdates(
ISetToken _setToken,
address _reserveAsset,
address _to,
ActionInfo memory _issueInfo
)
internal
{
_setToken.editPositionMultiplier(_issueInfo.newPositionMultiplier);
_setToken.editDefaultPosition(_reserveAsset, _issueInfo.newReservePositionUnit);
_setToken.mint(_to, _issueInfo.setTokenQuantity);
emit SetTokenNAVIssued(
address(_setToken),
msg.sender,
_to,
_reserveAsset,
address(navIssuanceSettings[_setToken].managerIssuanceHook),
_issueInfo.setTokenQuantity,
_issueInfo.managerFee,
_issueInfo.protocolFees
);
}
function _handleRedeemStateUpdates(
ISetToken _setToken,
address _reserveAsset,
address _to,
ActionInfo memory _redeemInfo
)
internal
{
_setToken.editPositionMultiplier(_redeemInfo.newPositionMultiplier);
_setToken.editDefaultPosition(_reserveAsset, _redeemInfo.newReservePositionUnit);
emit SetTokenNAVRedeemed(
address(_setToken),
msg.sender,
_to,
_reserveAsset,
address(navIssuanceSettings[_setToken].managerRedemptionHook),
_redeemInfo.setTokenQuantity,
_redeemInfo.managerFee,
_redeemInfo.protocolFees
);
}
function _handleRedemptionFees(ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo) internal {
// Instruct the SetToken to transfer protocol fee to fee recipient if there is a fee
payProtocolFeeFromSetToken(_setToken, _reserveAsset, _redeemInfo.protocolFees);
// Instruct the SetToken to transfer manager fee to manager fee recipient if there is a fee
if (_redeemInfo.managerFee > 0) {
_setToken.strictInvokeTransfer(
_reserveAsset,
navIssuanceSettings[_setToken].feeRecipient,
_redeemInfo.managerFee
);
}
}
/**
* Returns the issue premium percentage. Virtual function that can be overridden in future versions of the module
* and can contain arbitrary logic to calculate the issuance premium.
*/
function _getIssuePremium(
ISetToken _setToken,
address /* _reserveAsset */,
uint256 /* _reserveAssetquantity */
)
virtual
internal
view
returns (uint256)
{
return navIssuanceSettings[_setToken].premiumPercentage;
}
/**
* Returns the redeem premium percentage. Virtual function that can be overridden in future versions of the module
* and can contain arbitrary logic to calculate the redemption premium.
*/
function _getRedeemPremium(
ISetToken _setToken,
address /* _reserveAsset */,
uint256 /* _setTokenquantity */
)
virtual
internal
view
returns (uint256)
{
return navIssuanceSettings[_setToken].premiumPercentage;
}
/**
* Returns the fees attributed to the manager and the protocol. The fees are calculated as folows:
*
* ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity
* Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity
*
* @param _setToken Instance of the SetToken
* @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from
* @param _protocolManagerFeeIndex Index to pull rev share NAV Issuance fee from the Controller
* @param _protocolDirectFeeIndex Index to pull direct NAV issuance fee from the Controller
* @param _managerFeeIndex Index from NAVIssuanceSettings (0 = issue fee, 1 = redeem fee)
*
* @return uint256 Fees paid to the protocol in reserve asset
* @return uint256 Fees paid to the manager in reserve asset
* @return uint256 Net reserve to user net of fees
*/
function _getFees(
ISetToken _setToken,
uint256 _reserveAssetQuantity,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns (uint256, uint256, uint256)
{
(uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages(
_setToken,
_protocolManagerFeeIndex,
_protocolDirectFeeIndex,
_managerFeeIndex
);
// Calculate total notional fees
uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 netReserveFlow = _reserveAssetQuantity.sub(protocolFees).sub(managerFee);
return (protocolFees, managerFee, netReserveFlow);
}
function _getProtocolAndManagerFeePercentages(
ISetToken _setToken,
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 = navIssuanceSettings[_setToken].managerFees[_managerFeeIndex];
// Calculate revenue share split percentage
uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent);
uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage);
uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent);
return (managerRevenueSharePercentage, totalProtocolFeePercentage);
}
function _getSetTokenMintQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _netReserveFlows, // Value of reserve asset net of fees
uint256 _setTotalSupply
)
internal
view
returns (uint256)
{
uint256 premiumPercentage = _getIssuePremium(_setToken, _reserveAsset, _netReserveFlows);
uint256 premiumValue = _netReserveFlows.preciseMul(premiumPercentage);
// Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (10e18)
// Reverts if price is not found
uint256 setTokenValuation = controller.getSetValuer().calculateSetTokenValuation(_setToken, _reserveAsset);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals);
uint256 normalizedTotalReserveQuantityNetFeesAndPremium = _netReserveFlows.sub(premiumValue).preciseDiv(10 ** reserveAssetDecimals);
// Calculate SetTokens to mint to issuer
uint256 denominator = _setTotalSupply.preciseMul(setTokenValuation).add(normalizedTotalReserveQuantityNetFees).sub(normalizedTotalReserveQuantityNetFeesAndPremium);
return normalizedTotalReserveQuantityNetFeesAndPremium.preciseMul(_setTotalSupply).preciseDiv(denominator);
}
function _getRedeemReserveQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
internal
view
returns (uint256)
{
// Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (10e18)
// Reverts if price is not found
uint256 setTokenValuation = controller.getSetValuer().calculateSetTokenValuation(_setToken, _reserveAsset);
uint256 totalRedeemValueInPreciseUnits = _setTokenQuantity.preciseMul(setTokenValuation);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 prePremiumReserveQuantity = totalRedeemValueInPreciseUnits.preciseMul(10 ** reserveAssetDecimals);
uint256 premiumPercentage = _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity);
uint256 premiumQuantity = prePremiumReserveQuantity.preciseMulCeil(premiumPercentage);
return prePremiumReserveQuantity.sub(premiumQuantity);
}
/**
* The new position multiplier is calculated as follows:
* inflationPercentage = oldSupply / newSupply
* newMultiplier = (1 - inflationPercentage) * positionMultiplier
*/
function _getIssuePositionMultiplier(
ISetToken _setToken,
ActionInfo memory _issueInfo
)
internal
view
returns (uint256, int256)
{
// Calculate inflation and new position multiplier. Note: Round inflation up in order to round position multiplier down
uint256 newTotalSupply = _issueInfo.setTokenQuantity.add(_issueInfo.previousSetTokenSupply);
int256 inflation = _issueInfo.setTokenQuantity.preciseDivCeil(newTotalSupply).toInt256();
int256 newPositionMultiplier = PreciseUnitMath.preciseUnitInt().sub(inflation).preciseMul(_setToken.positionMultiplier());
return (newTotalSupply, newPositionMultiplier);
}
/**
* Calculate deflation and new position multiplier. Note: Round deflation down in order to round position multiplier down
*
* The new position multiplier is calculated as follows:
* deflationPercentage = oldSupply / newSupply
* newMultiplier = (1 + inflationPercentage) * positionMultiplier
*/
function _getRedeemPositionMultiplier(
ISetToken _setToken,
uint256 _setTokenQuantity,
ActionInfo memory _redeemInfo
)
internal
view
returns (uint256, int256)
{
uint256 newTotalSupply = _redeemInfo.previousSetTokenSupply.sub(_setTokenQuantity);
int256 deflation = _setTokenQuantity.preciseDiv(newTotalSupply).toInt256();
int256 newPositionMultiplier = PreciseUnitMath.preciseUnitInt().add(deflation).preciseMul(_setToken.positionMultiplier());
return (newTotalSupply, newPositionMultiplier);
}
/**
* The new position reserve asset unit is calculated as follows:
* totalReserve = (oldUnit * oldSetTokenSupply) + reserveQuantity
* newUnit = totalReserve / newSetTokenSupply
*/
function _getIssuePositionUnit(
ISetToken _setToken,
address _reserveAsset,
ActionInfo memory _issueInfo
)
internal
view
returns (uint256)
{
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
uint256 totalReserve = existingUnit
.preciseMul(_issueInfo.previousSetTokenSupply)
.add(_issueInfo.netFlowQuantity);
return totalReserve.preciseDiv(_issueInfo.newSetTokenSupply);
}
/**
* The new position reserve asset unit is calculated as follows:
* totalReserve = (oldUnit * oldSetTokenSupply) - reserveQuantityToSendOut
* newUnit = totalReserve / newSetTokenSupply
*/
function _getRedeemPositionUnit(
ISetToken _setToken,
address _reserveAsset,
ActionInfo memory _redeemInfo
)
internal
view
returns (uint256)
{
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
uint256 totalExistingUnits = existingUnit.preciseMul(_redeemInfo.previousSetTokenSupply);
uint256 outflow = _redeemInfo.netFlowQuantity.add(_redeemInfo.protocolFees).add(_redeemInfo.managerFee);
// Require withdrawable quantity is greater than existing collateral
require(totalExistingUnits >= outflow, "Must be greater than total available collateral");
return totalExistingUnits.sub(outflow).preciseDiv(_redeemInfo.newSetTokenSupply);
}
/**
* If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic
* can contain arbitrary logic including validations, external function calls, etc.
*/
function _callPreIssueHooks(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
address _caller,
address _to
)
internal
{
INAVIssuanceHook preIssueHook = navIssuanceSettings[_setToken].managerIssuanceHook;
if (address(preIssueHook) != address(0)) {
preIssueHook.invokePreIssueHook(_setToken, _reserveAsset, _reserveAssetQuantity, _caller, _to);
}
}
/**
* If a pre-redeem hook has been configured, call the external-protocol contract.
*/
function _callPreRedeemHooks(ISetToken _setToken, uint256 _setQuantity, address _caller, address _to) internal {
INAVIssuanceHook preRedeemHook = navIssuanceSettings[_setToken].managerRedemptionHook;
if (address(preRedeemHook) != address(0)) {
preRedeemHook.invokePreRedeemHook(_setToken, _setQuantity, _caller, _to);
}
}
} | * Checks if issue is valid @param _setToken Instance of the SetToken @param _reserveAsset Address of the reserve asset @param _reserveAssetQuantity Quantity of the reserve asset to issue with @return bool Returns true if issue is valid/ | function isIssueValid(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (bool)
{
uint256 setTotalSupply = _setToken.totalSupply();
if (
_reserveAssetQuantity == 0
|| !isReserveAsset[_setToken][_reserveAsset]
|| setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply
) {
return false;
}
return true;
}
| 6,802,807 | [
1,
4081,
309,
5672,
353,
923,
225,
389,
542,
1345,
5397,
5180,
434,
326,
1000,
1345,
225,
389,
455,
6527,
6672,
1171,
5267,
434,
326,
20501,
3310,
225,
389,
455,
6527,
6672,
12035,
540,
18189,
434,
326,
20501,
3310,
358,
5672,
598,
327,
225,
1426,
13491,
2860,
638,
309,
5672,
353,
923,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
353,
12956,
1556,
12,
203,
3639,
467,
694,
1345,
389,
542,
1345,
16,
203,
3639,
1758,
389,
455,
6527,
6672,
16,
203,
3639,
2254,
5034,
389,
455,
6527,
6672,
12035,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2254,
5034,
25015,
3088,
1283,
273,
389,
542,
1345,
18,
4963,
3088,
1283,
5621,
203,
203,
3639,
309,
261,
203,
5411,
389,
455,
6527,
6672,
12035,
422,
374,
203,
5411,
747,
401,
291,
607,
6527,
6672,
63,
67,
542,
1345,
6362,
67,
455,
6527,
6672,
65,
203,
5411,
747,
25015,
3088,
1283,
411,
8775,
7568,
89,
1359,
2628,
63,
67,
542,
1345,
8009,
1154,
694,
1345,
3088,
1283,
203,
3639,
262,
288,
203,
5411,
327,
629,
31,
203,
3639,
289,
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
] |
./full_match/3/0x49D4127D3E113C3CD8F15DdA959f36de8b66E2B9/sources/contracts/v2/TokenIssueV2.sol | * @dev Collection of functions related to the address type/ | library Address {
}
function isContract(address account) internal view returns (bool) {
uint256 size;
return size > 0;
}
assembly { size := extcodesize(account) }
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
require(success, "Address: unable to send value, recipient may have reverted");
}
(bool success, ) = recipient.call{ value: amount }("");
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) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
return _verifyCallResult(success, returndata, errorMessage);
}
(bool success, bytes memory returndata) = target.call{ value: value }(data);
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
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);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
} else {
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
} else {
}
| 14,225,070 | [
1,
2532,
434,
4186,
3746,
358,
326,
1758,
618,
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,
12083,
5267,
288,
203,
97,
203,
203,
565,
445,
353,
8924,
12,
2867,
2236,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
203,
3639,
2254,
5034,
963,
31,
203,
3639,
327,
963,
405,
374,
31,
203,
565,
289,
203,
203,
3639,
19931,
288,
963,
519,
1110,
7000,
554,
12,
4631,
13,
289,
203,
565,
445,
1366,
620,
12,
2867,
8843,
429,
8027,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
3844,
16,
315,
1887,
30,
2763,
11339,
11013,
8863,
203,
203,
3639,
2583,
12,
4768,
16,
315,
1887,
30,
13496,
358,
1366,
460,
16,
8027,
2026,
1240,
15226,
329,
8863,
203,
565,
289,
203,
203,
3639,
261,
6430,
2216,
16,
262,
273,
8027,
18,
1991,
95,
460,
30,
3844,
289,
2932,
8863,
203,
565,
445,
445,
1477,
12,
2867,
1018,
16,
1731,
3778,
501,
13,
2713,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
327,
445,
1477,
12,
3299,
16,
501,
16,
315,
1887,
30,
4587,
17,
2815,
745,
2535,
8863,
203,
565,
289,
203,
203,
565,
445,
445,
1477,
12,
2867,
1018,
16,
1731,
3778,
501,
16,
533,
3778,
9324,
13,
2713,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
327,
445,
26356,
620,
12,
3299,
16,
501,
16,
374,
16,
9324,
1769,
203,
565,
289,
203,
203,
565,
445,
445,
26356,
620,
12,
2867,
1018,
16,
1731,
3778,
501,
16,
2254,
5034,
460,
13,
2713,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
327,
445,
26356,
620,
12,
3299,
16,
501,
16,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.7 <0.9.0;
//import "../../utils/Context.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 Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
//import "@openzeppelin/contracts/access/Ownable.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);
}
}
//import "./IERC165.sol";
/**
* @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);
}
//import "./IERC721.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;
}
//import "./IERC721Receiver.sol";
/**
* @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);
}
//import "./extensions/IERC721Metadata.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);
}
//import "../../utils/Address.sol";
/**
* @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);
}
}
}
}
//import "../../utils/Strings.sol";
/**
* @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);
}
}
//import "../../utils/introspection/ERC165.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;
}
}
//import "@openzeppelin/contracts/token/ERC721/ERC721.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 {}
}
//import "./Common/StrLib.sol";
//--------------------------
// 文字列ライブラリ
//--------------------------
library StrLib {
//---------------------------
// 数値を10進数文字列にして返す
//---------------------------
function numToStr( uint256 val ) internal pure returns (string memory) {
// 数字の桁
uint256 len = 1;
uint256 temp = val;
while( temp >= 10 ){
temp = temp / 10;
len++;
}
// バッファ確保
bytes memory buf = new bytes(len);
// 数字の出力
temp = val;
for( uint256 i=0; i<len; i++ ){
uint c = 48 + (temp%10); // ascii: '0' 〜 '9'
buf[len-(i+1)] = bytes1(uint8(c));
temp /= 10;
}
return( string(buf) );
}
}
//-----------------------
// RAT-PTHR
//-----------------------
contract Token is Ownable, ERC721 {
//----------------------------------------------
// 定数
//----------------------------------------------
uint256 constant private TOKEN_ID_OFFSET = 1;
uint256 constant private TOKEN_MAX = 10296;
uint256 constant private MINT_MAX = 20;
address constant private OWNER_ADDRESS = 0xa15161F087854750e09a7571bbf43361d95Ed099;
address constant private LYNX_ADDRESS = 0x45ac1E44e84351Bf17418e481E52BBaC2f08C8b1;
string constant private TOKEN_NAME = "PAW THE HYPER RAT";
string constant private TOKEN_SYMBOL = "PTHR";
string constant private HASH_DIRECTORY = "QmX7DqpLzgNYyJcyyT9jJv94tZ8dyBswBFFw7yYeTixZ1i";
//----------------------------------------------
// 管理データ
//----------------------------------------------
uint256 private _total_supply;
// IPFSの修復
mapping( uint256 => string ) private _repaired_hashes; // 万一メタに問題があった場合の修復用
// キャンペーン
bool private _campaign_suspended; // 停止フラグ(何か問題があった場合)
uint256 private _campaign_id; // 現在のキャンペーンID
uint256 private _campaign_start; // キャンペーンの開始日時(unixtime)
uint256 private _campaign_period; // キャンペーンの期間(秒で指定する)
//----------------------------------------------
// ユーザー管理
//----------------------------------------------
mapping( address => uint256 ) private _last_campaign; // 最後にアクセスしたキャンペーン
mapping( address => uint256 ) private _num_minted; // 最後にアクセスしたキャンペーンでの発行数
//----------------------------------------------
// コンストラクタ
//----------------------------------------------
constructor() Ownable() ERC721( TOKEN_NAME, TOKEN_SYMBOL ) {
transferOwnership( OWNER_ADDRESS );
}
//----------------------------------------------
// [public] tokenURI
//----------------------------------------------
function tokenURI( uint256 tokenId ) public view override returns (string memory) {
require( _exists( tokenId ), "nonexistent token" );
// 修復データがあれば
string memory hash = repairedHash( tokenId );
if( bytes(hash).length > 0 ){
return( string( abi.encodePacked( "ipfs://", hash ) ) );
}
// ここまできたらリリース時のメタを返す
string memory strId = StrLib.numToStr( tokenId );
return( string( abi.encodePacked( "ipfs://", HASH_DIRECTORY, "/", strId ) ) );
}
//----------------------------------------------
// [external] RATのMINT
//----------------------------------------------
function mintTokens( uint256 numMint ) external {
// 中断中ではないか?
require( !_campaign_suspended, "campaign suspended" );
// キャンペーンが有効か?
require( _campaign_id > 0, "invalid campaign id" );
// 開始時間に達しているか?
require( _campaign_start <= block.timestamp, "campaign not started" );
// 終了時間を過ぎていないか?
require( (_campaign_start+_campaign_period) > block.timestamp, "campaign expired" );
// 回数が有効か?
require( numMint > 0 && numMint <= MINT_MAX, "invalid numMint" );
// RATの残りはあるか?
require( TOKEN_MAX >= (_total_supply+numMint), "remaining rat not enough" );
// キャンペーンを跨いでいたらユーザー情報のリセット
if( _last_campaign[msg.sender] < _campaign_id ){
_last_campaign[msg.sender] = _campaign_id;
_num_minted[msg.sender] = 0;
}
// LYNXの保有数の確認
IERC721 lynxContract = IERC721( LYNX_ADDRESS );
uint256 numLynx = lynxContract.balanceOf( msg.sender );
// LYNXの保有数は足りているか?
require( numLynx >= (_num_minted[msg.sender]+numMint), "lynx not enough" );
//----------------------
// チェック完了
//----------------------
// 発行
for( uint256 i=0; i<numMint; i++ ){
_safeMint( msg.sender, TOKEN_ID_OFFSET + _total_supply );
_total_supply++;
}
// 引いた数の加算
_num_minted[msg.sender] += numMint;
}
//----------------------------------------------
// [external/onlyOwner] RATのGiveAway
//----------------------------------------------
function giveawayTokens( address to, uint256 numMint ) external onlyOwner {
// RATの残りはあるか?
require( TOKEN_MAX >= (_total_supply+numMint), "remaining rat not enough" );
//----------------------
// チェック完了
//----------------------
// 発行
for( uint256 i=0; i<numMint; i++ ){
_safeMint( to, TOKEN_ID_OFFSET + _total_supply );
_total_supply++;
}
}
//---------------------------------------------------
// [external] 発行数の確認
//---------------------------------------------------
function totalSupply() external view returns (uint256) {
return( _total_supply );
}
//---------------------------------------------------
// [public] 修復されたメタハッシュの確認
//---------------------------------------------------
function repairedHash( uint256 tokenId ) public view returns (string memory) {
require( _exists( tokenId ), "nonexistent token" );
return( _repaired_hashes[tokenId] );
}
//---------------------------------------------------
// [external/onlyOwner] メタデータのハッシュの修復
//---------------------------------------------------
function repairHash( uint256 tokenId, string calldata hash ) external onlyOwner {
require( _exists( tokenId ), "nonexistent token" );
_repaired_hashes[tokenId] = hash;
}
//---------------------------------------------------
// [external] キャンペーンの中断確認
//---------------------------------------------------
function campaignSuspended() external view returns (bool) {
return( _campaign_suspended );
}
//---------------------------------------------------
// [external/onlyOwner] キャンペーンの中断
//---------------------------------------------------
function setCampaignSuspended( bool flag ) external onlyOwner {
_campaign_suspended = flag;
}
//---------------------------------------------------
// [external] キャンペーンの内容確認
//---------------------------------------------------
function campaignId() external view returns (uint256) {
return( _campaign_id );
}
function campaignStart() external view returns (uint256) {
return( _campaign_start );
}
function campaignPeriod() external view returns (uint256) {
return( _campaign_period );
}
function blockTimestamp() external view returns (uint256) {
return( block.timestamp );
}
//---------------------------------------------------
// [external/onlyOwner] キャンペーンの設定
//---------------------------------------------------
function setCampaign( uint256 id, uint256 start, uint256 period ) external onlyOwner {
_campaign_id = id;
_campaign_start = start;
_campaign_period = period;
}
//---------------------------------------------------
// [external] キャンペーン中か?(ここは中断フラグをみない)
//---------------------------------------------------
function duringCampaign() external view returns (bool) {
if( _campaign_start <= block.timestamp ){
if( (_campaign_start+_campaign_period) > block.timestamp ){
return( true );
}
}
return( false );
}
//---------------------------------------------------
// [external] キャンペーンまでの待ち時間
//---------------------------------------------------
function waitingTimeForCampaign() external view returns (uint256) {
if( _campaign_start <= block.timestamp ){
return( 0 );
}
return( _campaign_start - block.timestamp );
}
//---------------------------------------------------
// [external] キャンペーンの残り時間
//---------------------------------------------------
function remainingTimeOfCampaign() external view returns (uint256) {
if( (_campaign_start+_campaign_period) <= block.timestamp ){
return( 0 );
}
// キャンペーン前であれば期間をそのまま返す(待ち時間は考慮にいれない)
if( _campaign_start > block.timestamp ){
return( _campaign_period );
}
return( (_campaign_start+_campaign_period) - block.timestamp );
}
//---------------------------------------------------
// [external] ユーザー情報の確認:保有LYNX
//---------------------------------------------------
function checkNumLynx( address target ) external view returns (uint256) {
IERC721 lynxContract = IERC721( LYNX_ADDRESS );
return( lynxContract.balanceOf( target ) );
}
//---------------------------------------------------
// [external] ユーザー情報の確認:引ける回数
//---------------------------------------------------
function checkNumMintable( address target ) external view returns (uint256) {
uint256 minted = 0;
// キャンペーンを跨いでいなければ持ち越し(キャンペーンIDが逆戻ることはない想定)
if( _last_campaign[target] >= _campaign_id ){
minted = _num_minted[target];
}
IERC721 lynxContract = IERC721( LYNX_ADDRESS );
uint256 numLynx = lynxContract.balanceOf( target );
if( numLynx <= minted ){
return( 0 );
}
return( numLynx - minted );
}
//---------------------------------------------------
// [external] ユーザー情報の確認:引いた回数
//---------------------------------------------------
function checkNumMinted( address target ) external view returns (uint256) {
if( _last_campaign[target] < _campaign_id ){
return( 0 );
}
return( _num_minted[target] );
}
} | ----------------------- RAT-PTHR--------------------------------------------------------------------- 定数-------------------------------------------------------------------------------------------- 管理データ---------------------------------------------- IPFSの修復 キャンペーン---------------------------------------------- ユーザー管理-------------------------------------------------------------------------------------------- コンストラクタ---------------------------------------------- | contract Token is Ownable, ERC721 {
uint256 constant private TOKEN_ID_OFFSET = 1;
uint256 constant private TOKEN_MAX = 10296;
uint256 constant private MINT_MAX = 20;
address constant private OWNER_ADDRESS = 0xa15161F087854750e09a7571bbf43361d95Ed099;
address constant private LYNX_ADDRESS = 0x45ac1E44e84351Bf17418e481E52BBaC2f08C8b1;
string constant private TOKEN_NAME = "PAW THE HYPER RAT";
string constant private TOKEN_SYMBOL = "PTHR";
string constant private HASH_DIRECTORY = "QmX7DqpLzgNYyJcyyT9jJv94tZ8dyBswBFFw7yYeTixZ1i";
uint256 private _total_supply;
constructor() Ownable() ERC721( TOKEN_NAME, TOKEN_SYMBOL ) {
transferOwnership( OWNER_ADDRESS );
}
function tokenURI( uint256 tokenId ) public view override returns (string memory) {
require( _exists( tokenId ), "nonexistent token" );
string memory hash = repairedHash( tokenId );
if( bytes(hash).length > 0 ){
}
}
function tokenURI( uint256 tokenId ) public view override returns (string memory) {
require( _exists( tokenId ), "nonexistent token" );
string memory hash = repairedHash( tokenId );
if( bytes(hash).length > 0 ){
}
}
string memory strId = StrLib.numToStr( tokenId );
function mintTokens( uint256 numMint ) external {
require( !_campaign_suspended, "campaign suspended" );
require( _campaign_id > 0, "invalid campaign id" );
require( _campaign_start <= block.timestamp, "campaign not started" );
require( (_campaign_start+_campaign_period) > block.timestamp, "campaign expired" );
require( numMint > 0 && numMint <= MINT_MAX, "invalid numMint" );
require( TOKEN_MAX >= (_total_supply+numMint), "remaining rat not enough" );
if( _last_campaign[msg.sender] < _campaign_id ){
_last_campaign[msg.sender] = _campaign_id;
_num_minted[msg.sender] = 0;
}
uint256 numLynx = lynxContract.balanceOf( msg.sender );
for( uint256 i=0; i<numMint; i++ ){
_safeMint( msg.sender, TOKEN_ID_OFFSET + _total_supply );
_total_supply++;
}
}
function mintTokens( uint256 numMint ) external {
require( !_campaign_suspended, "campaign suspended" );
require( _campaign_id > 0, "invalid campaign id" );
require( _campaign_start <= block.timestamp, "campaign not started" );
require( (_campaign_start+_campaign_period) > block.timestamp, "campaign expired" );
require( numMint > 0 && numMint <= MINT_MAX, "invalid numMint" );
require( TOKEN_MAX >= (_total_supply+numMint), "remaining rat not enough" );
if( _last_campaign[msg.sender] < _campaign_id ){
_last_campaign[msg.sender] = _campaign_id;
_num_minted[msg.sender] = 0;
}
uint256 numLynx = lynxContract.balanceOf( msg.sender );
for( uint256 i=0; i<numMint; i++ ){
_safeMint( msg.sender, TOKEN_ID_OFFSET + _total_supply );
_total_supply++;
}
}
IERC721 lynxContract = IERC721( LYNX_ADDRESS );
require( numLynx >= (_num_minted[msg.sender]+numMint), "lynx not enough" );
function mintTokens( uint256 numMint ) external {
require( !_campaign_suspended, "campaign suspended" );
require( _campaign_id > 0, "invalid campaign id" );
require( _campaign_start <= block.timestamp, "campaign not started" );
require( (_campaign_start+_campaign_period) > block.timestamp, "campaign expired" );
require( numMint > 0 && numMint <= MINT_MAX, "invalid numMint" );
require( TOKEN_MAX >= (_total_supply+numMint), "remaining rat not enough" );
if( _last_campaign[msg.sender] < _campaign_id ){
_last_campaign[msg.sender] = _campaign_id;
_num_minted[msg.sender] = 0;
}
uint256 numLynx = lynxContract.balanceOf( msg.sender );
for( uint256 i=0; i<numMint; i++ ){
_safeMint( msg.sender, TOKEN_ID_OFFSET + _total_supply );
_total_supply++;
}
}
_num_minted[msg.sender] += numMint;
function giveawayTokens( address to, uint256 numMint ) external onlyOwner {
require( TOKEN_MAX >= (_total_supply+numMint), "remaining rat not enough" );
for( uint256 i=0; i<numMint; i++ ){
_safeMint( to, TOKEN_ID_OFFSET + _total_supply );
_total_supply++;
}
}
function giveawayTokens( address to, uint256 numMint ) external onlyOwner {
require( TOKEN_MAX >= (_total_supply+numMint), "remaining rat not enough" );
for( uint256 i=0; i<numMint; i++ ){
_safeMint( to, TOKEN_ID_OFFSET + _total_supply );
_total_supply++;
}
}
function totalSupply() external view returns (uint256) {
return( _total_supply );
}
function repairedHash( uint256 tokenId ) public view returns (string memory) {
require( _exists( tokenId ), "nonexistent token" );
return( _repaired_hashes[tokenId] );
}
function repairHash( uint256 tokenId, string calldata hash ) external onlyOwner {
require( _exists( tokenId ), "nonexistent token" );
_repaired_hashes[tokenId] = hash;
}
function campaignSuspended() external view returns (bool) {
return( _campaign_suspended );
}
function setCampaignSuspended( bool flag ) external onlyOwner {
_campaign_suspended = flag;
}
function campaignId() external view returns (uint256) {
return( _campaign_id );
}
function campaignStart() external view returns (uint256) {
return( _campaign_start );
}
function campaignPeriod() external view returns (uint256) {
return( _campaign_period );
}
function blockTimestamp() external view returns (uint256) {
return( block.timestamp );
}
function setCampaign( uint256 id, uint256 start, uint256 period ) external onlyOwner {
_campaign_id = id;
_campaign_start = start;
_campaign_period = period;
}
function duringCampaign() external view returns (bool) {
if( _campaign_start <= block.timestamp ){
if( (_campaign_start+_campaign_period) > block.timestamp ){
return( true );
}
}
return( false );
}
function duringCampaign() external view returns (bool) {
if( _campaign_start <= block.timestamp ){
if( (_campaign_start+_campaign_period) > block.timestamp ){
return( true );
}
}
return( false );
}
function duringCampaign() external view returns (bool) {
if( _campaign_start <= block.timestamp ){
if( (_campaign_start+_campaign_period) > block.timestamp ){
return( true );
}
}
return( false );
}
function waitingTimeForCampaign() external view returns (uint256) {
if( _campaign_start <= block.timestamp ){
return( 0 );
}
return( _campaign_start - block.timestamp );
}
function waitingTimeForCampaign() external view returns (uint256) {
if( _campaign_start <= block.timestamp ){
return( 0 );
}
return( _campaign_start - block.timestamp );
}
function remainingTimeOfCampaign() external view returns (uint256) {
if( (_campaign_start+_campaign_period) <= block.timestamp ){
return( 0 );
}
if( _campaign_start > block.timestamp ){
return( _campaign_period );
}
return( (_campaign_start+_campaign_period) - block.timestamp );
}
function remainingTimeOfCampaign() external view returns (uint256) {
if( (_campaign_start+_campaign_period) <= block.timestamp ){
return( 0 );
}
if( _campaign_start > block.timestamp ){
return( _campaign_period );
}
return( (_campaign_start+_campaign_period) - block.timestamp );
}
function remainingTimeOfCampaign() external view returns (uint256) {
if( (_campaign_start+_campaign_period) <= block.timestamp ){
return( 0 );
}
if( _campaign_start > block.timestamp ){
return( _campaign_period );
}
return( (_campaign_start+_campaign_period) - block.timestamp );
}
function checkNumLynx( address target ) external view returns (uint256) {
IERC721 lynxContract = IERC721( LYNX_ADDRESS );
return( lynxContract.balanceOf( target ) );
}
function checkNumMintable( address target ) external view returns (uint256) {
uint256 minted = 0;
if( _last_campaign[target] >= _campaign_id ){
minted = _num_minted[target];
}
IERC721 lynxContract = IERC721( LYNX_ADDRESS );
uint256 numLynx = lynxContract.balanceOf( target );
if( numLynx <= minted ){
return( 0 );
}
return( numLynx - minted );
}
function checkNumMintable( address target ) external view returns (uint256) {
uint256 minted = 0;
if( _last_campaign[target] >= _campaign_id ){
minted = _num_minted[target];
}
IERC721 lynxContract = IERC721( LYNX_ADDRESS );
uint256 numLynx = lynxContract.balanceOf( target );
if( numLynx <= minted ){
return( 0 );
}
return( numLynx - minted );
}
function checkNumMintable( address target ) external view returns (uint256) {
uint256 minted = 0;
if( _last_campaign[target] >= _campaign_id ){
minted = _num_minted[target];
}
IERC721 lynxContract = IERC721( LYNX_ADDRESS );
uint256 numLynx = lynxContract.balanceOf( target );
if( numLynx <= minted ){
return( 0 );
}
return( numLynx - minted );
}
function checkNumMinted( address target ) external view returns (uint256) {
if( _last_campaign[target] < _campaign_id ){
return( 0 );
}
return( _num_minted[target] );
}
function checkNumMinted( address target ) external view returns (uint256) {
if( _last_campaign[target] < _campaign_id ){
return( 0 );
}
return( _num_minted[target] );
}
} | 10,122,795 | [
1,
1271,
17082,
534,
789,
17,
1856,
15024,
5802,
13465,
225,
166,
111,
253,
167,
248,
113,
28253,
7620,
225,
168,
111,
99,
168,
243,
233,
164,
230,
234,
164,
230,
125,
164,
229,
128,
2443,
17908,
2971,
4931,
164,
228,
111,
165,
128,
111,
166,
127,
107,
225,
164,
229,
260,
164,
230,
101,
164,
230,
116,
164,
230,
253,
164,
230,
125,
164,
230,
116,
2443,
17908,
225,
164,
230,
104,
164,
230,
125,
164,
229,
119,
164,
230,
125,
168,
111,
99,
168,
243,
233,
28253,
7620,
225,
164,
229,
116,
164,
230,
116,
164,
229,
122,
164,
230,
235,
164,
230,
107,
164,
229,
112,
164,
229,
128,
2443,
17908,
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,
16351,
3155,
353,
14223,
6914,
16,
4232,
39,
27,
5340,
288,
203,
565,
2254,
5034,
5381,
3238,
14275,
67,
734,
67,
11271,
273,
404,
31,
203,
565,
2254,
5034,
5381,
3238,
14275,
67,
6694,
273,
1728,
5540,
26,
31,
203,
565,
2254,
5034,
5381,
3238,
490,
3217,
67,
6694,
273,
4200,
31,
203,
565,
1758,
5381,
3238,
531,
22527,
67,
15140,
273,
374,
6995,
3600,
31899,
42,
6840,
8285,
6564,
27,
3361,
73,
5908,
69,
5877,
11212,
9897,
74,
24,
3707,
9498,
72,
8778,
2671,
20,
2733,
31,
203,
565,
1758,
5381,
3238,
511,
61,
17106,
67,
15140,
273,
374,
92,
7950,
1077,
21,
41,
6334,
73,
5193,
4763,
21,
38,
74,
28686,
2643,
73,
8875,
21,
41,
9401,
9676,
69,
39,
22,
74,
6840,
39,
28,
70,
21,
31,
203,
565,
533,
5381,
3238,
14275,
67,
1985,
273,
315,
4066,
59,
12786,
29684,
3194,
534,
789,
14432,
203,
565,
533,
5381,
3238,
14275,
67,
22093,
273,
315,
1856,
15024,
14432,
203,
565,
533,
5381,
3238,
20857,
67,
17229,
273,
315,
53,
81,
60,
27,
40,
14166,
48,
94,
75,
50,
61,
93,
46,
2431,
93,
56,
29,
78,
46,
90,
11290,
88,
62,
28,
15680,
38,
5328,
38,
2246,
91,
27,
93,
61,
73,
56,
697,
62,
21,
77,
14432,
377,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
67,
2859,
1283,
31,
203,
203,
203,
203,
203,
565,
3885,
1435,
14223,
6914,
1435,
4232,
39,
27,
5340,
12,
14275,
67,
1985,
16,
14275,
67,
22093,
262,
288,
203,
3639,
7412,
5460,
12565,
2
] |
//Address: 0xd1670c55f5e68fede5fddd8ace64a3329f778b89
//Contract name: ATSTokenReservation
//Balance: 215.853806028 Ether
//Verification Date: 5/30/2018
//Transacion Count: 81
// CODE STARTS HERE
pragma solidity ^0.4.23;
/*
* Contract accepting reservations for ATS tokens.
* The actual tokens are not yet created and distributed due to non-technical reasons.
* This contract is used to collect funds for the ATS token sale and to transparently document that on a blockchain.
* It is tailored to allow a simple user journey while keeping complexity minimal.
* Once the privileged "state controller" sets the state to "Open", anybody can send Ether to the contract.
* Only Ether sent from whitelisted addresses is accepted for future ATS token conversion.
* The whitelisting is done by a dedicated whitelist controller.
* Whitelisting can take place asynchronously - that is, participants don't need to wait for the whitelisting to
* succeed before sending funds. This is a technical detail which allows for a smoother user journey.
* The state controller can switch to synchronous whitelisting (no Ether accepted from accounts not whitelisted before).
* Participants can trigger refunding during the Open state by making a transfer of 0 Ether.
* Funds of those not whitelisted (not accepted) are never locked, they can trigger refund beyond Open state.
* Only in Over state can whitelisted Ether deposits be fetched from the contract.
*
* When setting the state to Open, the state controller specifies a minimal timeframe for this state.
* Transition to the next state (Locked) is not possible (enforced by the contract).
* This gives participants the guarantee that they can get their full deposits refunded anytime and independently
* of the will of anybody else during that timeframe.
* (Note that this is true only as long as the whole process takes place before the date specified by FALLBACK_FETCH_FUNDS_TS)
*
* Ideally, there's no funds left in the contract once the state is set to Over and the accepted deposits were fetched.
* Since this can't really be foreseen, there's a fallback which allows to fetch all remaining Ether
* to a pre-specified address after a pre-specified date.
*
* Static analysis: block.timestamp is not used in a way which gives miners leeway for taking advantage.
*
* see https://code.lab10.io/graz/04-artis/artis/issues/364 for task evolution
*/
contract ATSTokenReservation {
// ################### DATA STRUCTURES ###################
enum States {
Init, // initial state. Contract is deployed, but deposits not yet accepted
Open, // open for token reservations. Refunds possible for all
Locked, // open for token reservations. Refunds locked for accepted deposits
Over // contract has done its duty. Funds payout can be triggered by state controller
}
// ################### CONSTANTS ###################
// 1. Oct 2018
uint32 FALLBACK_PAYOUT_TS = 1538352000;
// ################### STATE VARIABLES ###################
States public state = States.Init;
// privileged account: switch contract state, change config, whitelisting, trigger payout, ...
address public stateController;
// privileged account: whitelisting
address public whitelistController;
// Collected funds can be transferred only to this address. Is set in constructor.
address public payoutAddress;
// accepted deposits (received from whitelisted accounts)
uint256 public cumAcceptedDeposits = 0;
// not (yet) accepted deposits (received from non-whitelisted accounts)
uint256 public cumAlienDeposits = 0;
// cap for how much we accept (since the amount of tokens sold is also capped)
uint256 public maxCumAcceptedDeposits = 1E9 * 1E18; // pre-set to effectively unlimited (> existing ETH)
uint256 public minDeposit = 0.1 * 1E18; // lower bound per participant (can be a kind of spam protection)
uint256 minLockingTs; // earliest possible start of "locked" phase
// whitelisted addresses (those having "accepted" deposits)
mapping (address => bool) public whitelist;
// the state controller can set this in order to disallow deposits from addresses not whitelisted before
bool public requireWhitelistingBeforeDeposit = false;
// tracks accepted deposits (whitelisted accounts)
mapping (address => uint256) public acceptedDeposits;
// tracks alien (not yet accepted) deposits (non-whitelisted accounts)
mapping (address => uint256) public alienDeposits;
// ################### EVENTS ###################
// emitted events transparently document the open funding activities.
// only deposits made by whitelisted accounts (and not followed by a refund) count.
event StateTransition(States oldState, States newState);
event Whitelisted(address addr);
event Deposit(address addr, uint256 amount);
event Refund(address addr, uint256 amount);
// emitted when the accepted deposits are fetched to an account controlled by the ATS token provider
event FetchedDeposits(uint256 amount);
// ################### MODIFIERS ###################
modifier onlyStateControl() { require(msg.sender == stateController, "no permission"); _; }
modifier onlyWhitelistControl() {
require(msg.sender == stateController || msg.sender == whitelistController, "no permission");
_;
}
modifier requireState(States _requiredState) { require(state == _requiredState, "wrong state"); _; }
// ################### CONSTRUCTOR ###################
// the contract creator is set as stateController
constructor(address _whitelistController, address _payoutAddress) public {
whitelistController = _whitelistController;
payoutAddress = _payoutAddress;
stateController = msg.sender;
}
// ################### FALLBACK FUNCTION ###################
// implements the deposit and refund actions.
function () payable public {
if(msg.value > 0) {
require(state == States.Open || state == States.Locked);
if(requireWhitelistingBeforeDeposit) {
require(whitelist[msg.sender] == true, "not whitelisted");
}
tryDeposit();
} else {
tryRefund();
}
}
// ################### PUBLIC FUNCTIONS ###################
function stateSetOpen(uint32 _minLockingTs) public
onlyStateControl
requireState(States.Init)
{
minLockingTs = _minLockingTs;
setState(States.Open);
}
function stateSetLocked() public
onlyStateControl
requireState(States.Open)
{
require(block.timestamp >= minLockingTs);
setState(States.Locked);
}
function stateSetOver() public
onlyStateControl
requireState(States.Locked)
{
setState(States.Over);
}
// state controller can change the cap. Reducing possible only if not below current deposits
function updateMaxAcceptedDeposits(uint256 _newMaxDeposits) public onlyStateControl {
require(cumAcceptedDeposits <= _newMaxDeposits);
maxCumAcceptedDeposits = _newMaxDeposits;
}
// new limit to be enforced for future deposits
function updateMinDeposit(uint256 _newMinDeposit) public onlyStateControl {
minDeposit = _newMinDeposit;
}
// option to switch between async and sync whitelisting
function setRequireWhitelistingBeforeDeposit(bool _newState) public onlyStateControl {
requireWhitelistingBeforeDeposit = _newState;
}
// Since whitelisting can occur asynchronously, an account to be whitelisted may already have deposited Ether.
// In this case the deposit is converted form alien to accepted.
// Since the deposit logic depends on the whitelisting status and since transactions are processed sequentially,
// it's ensured that at any time an account can have either (XOR) no or alien or accepted deposits and that
// the whitelisting status corresponds to the deposit status (not_whitelisted <-> alien | whitelisted <-> accepted).
// This function is idempotent.
function addToWhitelist(address _addr) public onlyWhitelistControl {
if(whitelist[_addr] != true) {
// if address has alien deposit: convert it to accepted
if(alienDeposits[_addr] > 0) {
cumAcceptedDeposits += alienDeposits[_addr];
acceptedDeposits[_addr] += alienDeposits[_addr];
cumAlienDeposits -= alienDeposits[_addr];
delete alienDeposits[_addr]; // needs to be the last statement in this block!
}
whitelist[_addr] = true;
emit Whitelisted(_addr);
}
}
// Option for batched whitelisting (for times with crowded chain).
// caller is responsible to not blow gas limit with too many addresses at once
function batchAddToWhitelist(address[] _addresses) public onlyWhitelistControl {
for (uint i = 0; i < _addresses.length; i++) {
addToWhitelist(_addresses[i]);
}
}
// transfers an alien deposit back to the sender
function refundAlienDeposit(address _addr) public onlyWhitelistControl {
// Note: this implementation requires that alienDeposits has a primitive value type.
// With a complex type, this code would produce a dangling reference.
uint256 withdrawAmount = alienDeposits[_addr];
require(withdrawAmount > 0);
delete alienDeposits[_addr]; // implies setting the value to 0
cumAlienDeposits -= withdrawAmount;
emit Refund(_addr, withdrawAmount);
_addr.transfer(withdrawAmount); // throws on failure
}
// payout of the accepted deposits to the pre-designated address, available once it's all over
function payout() public
onlyStateControl
requireState(States.Over)
{
uint256 amount = cumAcceptedDeposits;
cumAcceptedDeposits = 0;
emit FetchedDeposits(amount);
payoutAddress.transfer(amount);
// not idempotent, but multiple invocation would just trigger zero-transfers
}
// After the specified date, any of the privileged/special accounts can trigger payment of remaining funds
// to the payoutAddress. This is a safety net to minimize the risk of funds remaining stuck.
// It's not yet clear what we can / should / are allowed to do with alien deposits which aren't reclaimed.
// With this fallback in place, we have for example the option to donate them at some point.
function fallbackPayout() public {
require(msg.sender == stateController || msg.sender == whitelistController || msg.sender == payoutAddress);
require(block.timestamp > FALLBACK_PAYOUT_TS);
payoutAddress.transfer(address(this).balance);
}
// ################### INTERNAL FUNCTIONS ###################
// rule enforcement and book-keeping for incoming deposits
function tryDeposit() internal {
require(cumAcceptedDeposits + msg.value <= maxCumAcceptedDeposits);
if(whitelist[msg.sender] == true) {
require(acceptedDeposits[msg.sender] + msg.value >= minDeposit);
acceptedDeposits[msg.sender] += msg.value;
cumAcceptedDeposits += msg.value;
} else {
require(alienDeposits[msg.sender] + msg.value >= minDeposit);
alienDeposits[msg.sender] += msg.value;
cumAlienDeposits += msg.value;
}
emit Deposit(msg.sender, msg.value);
}
// rule enforcement and book-keeping for refunding requests
function tryRefund() internal {
// Note: this implementation requires that acceptedDeposits and alienDeposits have a primitive value type.
// With a complex type, this code would produce dangling references.
uint256 withdrawAmount;
if(whitelist[msg.sender] == true) {
require(state == States.Open);
withdrawAmount = acceptedDeposits[msg.sender];
require(withdrawAmount > 0);
delete acceptedDeposits[msg.sender]; // implies setting the value to 0
cumAcceptedDeposits -= withdrawAmount;
} else {
// alien deposits can be withdrawn anytime (we prefer to not touch them)
withdrawAmount = alienDeposits[msg.sender];
require(withdrawAmount > 0);
delete alienDeposits[msg.sender]; // implies setting the value to 0
cumAlienDeposits -= withdrawAmount;
}
emit Refund(msg.sender, withdrawAmount);
// do the actual transfer last as recommended since the DAO incident (Checks-Effects-Interaction pattern)
msg.sender.transfer(withdrawAmount); // throws on failure
}
function setState(States _newState) internal {
state = _newState;
emit StateTransition(state, _newState);
}
}
| not (yet) accepted deposits (received from non-whitelisted accounts) | uint256 public cumAlienDeposits = 0;
| 1,041,342 | [
1,
902,
261,
24404,
13,
8494,
443,
917,
1282,
261,
15213,
628,
1661,
17,
20409,
329,
9484,
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
] | [
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,
2254,
5034,
1071,
14471,
37,
549,
275,
758,
917,
1282,
273,
374,
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,
-100
] |
pragma experimental ABIEncoderV2;
pragma solidity ^0.8.4;
//SPDX-License-Identifier: MIT
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777.sol";
import "./interfaces/DInterestInterface.sol";
import "./interfaces/CErc20.sol";
import "./interfaces/IVesting02.sol";
import "./Accounts.sol";
contract StakeManager is Ownable, IERC721Receiver {
struct mphStruct {
address owner;
bool isStaking;
uint64 maturation;
uint64 mphID;
uint64 vestID;
uint256 stakedAmount;
}
struct cmpStruct {
address owner;
bool isStaking;
uint64 maturation;
uint256 cDAIAmount;
}
mapping(address => mphStruct) private addressToMph;
mapping(address => cmpStruct) private addressToCmp;
mapping(address => mapping(uint64 => uint64)) private depositIDToVestID;
mapping(address => uint8) addressToAccountType;
//0: not staking, 1: MPH staking, 2: CMP staking
mapping(address => uint8) private addressToStakeType;
string public name = "StakeManager";
string public laVieImage =
"https://siasky.net/BABQrpPo_hBwLBqVZP9LEc44f96zzi1KVXsW9GIqS2MmkQ";
// LavToken public lavToken;
//Mainnet Ethereum
// address private constant DInterestPoolAddress =
// 0x11B1c87983F881B3686F8b1171628357FAA30038;
// address private constant IVesting02Address =
// 0x137C9A85Cde23318E3fA8d4E486cD62F46095cc8;
// address private constant MphAddress =
// 0x8888801aF4d980682e47f1A9036e589479e835C5;
// RINKEBY
address private constant DInterestPoolAddress =
0x71482F8cD0e956051208603709639FA28cBc1F33;
address private constant IVesting02Address =
// 0xa0C5d33E86C6484B37aDe25dbA5056100F3133D0;
0xab5bAA840b4C9321aa66144ffB2693E2db1166C7;
address private constant MphAddress =
0xC79a56Af51Ec36738E965e88100e4570c5C77A93;
address private constant cDAIAddress =
0x6D7F0754FFeb405d23C51CE938289d4835bE3b14;
address private constant DAIAddress =
0x5592EC0cfb4dbc12D3aB100b257153436a1f0FEa;
address private constant laVxAddress =
0x71b4f145617410eE50DC26d224D202e9278D71f1;
event Stake1(mphStruct nft);
event Stake2(cmpStruct nft);
event Unstake(address to, uint256 amount);
event MyLog(string, uint256);
DInterestInterface pool;
IVesting02 vesting;
IERC20 Mph;
CErc20 cDAI;
IERC20 daiToken;
IERC20 LaVxToken;
constructor() {
daiToken = IERC20(DAIAddress);
pool = DInterestInterface(DInterestPoolAddress);
vesting = IVesting02(IVesting02Address);
Mph = IERC20(MphAddress);
cDAI = CErc20(cDAIAddress);
LaVxToken = IERC20(laVxAddress);
}
/// Core function shells
function stake(
address player,
uint256 amount,
uint256 timeInDays,
uint8 stakeType
) external onlyOwner {
uint256 allowance = daiToken.allowance(player, address(this));
require(allowance >= amount, "La Vie: Check the token allowance");
require(timeInDays <= 365, "La Vie: Above maximum days");
require(
amount > 0 && daiToken.balanceOf(player) >= amount,
"La Vie: Not enough DAI tokens"
);
// transfer
daiToken.transferFrom(player, payable(address(this)), amount);
console.log("transfered");
if (stakeType == 1) {
supplyDAITo88MPH(player, amount, timeInDays, stakeType);
} else if (stakeType == 2) {
supplyDAIToCompound(player, amount, timeInDays, stakeType);
}
}
function unstake(address player) external onlyOwner {
require(
addressToStakeType[player] != 0,
"La Vie: Not currently staking!"
);
if (addressToStakeType[player] == 1) {
redeemDAIFrom88mph(player);
} else if (addressToStakeType[player] == 2) {
redeemDAIFromCMP(player);
}
}
function supplyDAITo88MPH(
address player,
uint256 amount,
uint256 timeInDays,
uint8 stakeType
) private {
require(!(addressToMph[player].isStaking), "La Vie: Already staking!");
uint64 maturationTimestamp = uint64(
block.timestamp + (timeInDays * 1 days)
);
console.log(maturationTimestamp);
require(daiToken.approve(address(pool), amount));
console.log("approved");
(uint64 depositID, ) = pool.deposit(
amount,
maturationTimestamp
// 0
// laVieImage
);
console.log(depositID);
console.log("mph deposit");
// uint64 vestingID = vesting.getVestID(player, depositID);
// console.log("vesting ID: %s",vestingID);
addressToMph[player].owner = player;
addressToMph[player].isStaking = true;
addressToMph[player].maturation = maturationTimestamp;
addressToMph[player].mphID = depositID;
// addressToMph[player].vestID = vestingID;
addressToMph[player].stakedAmount = amount;
console.log(
"Mph struct of ID: %s with maturation of %s",
addressToMph[player].mphID,
// addressToMph[player].vestID,
addressToMph[player].maturation
);
console.log("depositID for %s : %s ", player, depositID);
addressToStakeType[player] = stakeType;
emit Stake1(addressToMph[msg.sender]);
}
function supplyDAIToCompound(
address player,
uint256 amount,
uint256 timeInDays,
uint8 stakeType
) private returns (uint256) {
require(!(addressToCmp[player].isStaking), "La Vie: Already staking!");
uint64 maturationTimestamp = uint64(
block.timestamp + (timeInDays * 1 days)
);
// Amount of current exchange rate from cToken to underlying
uint256 exchangeRateMantissa = cDAI.exchangeRateCurrent();
emit MyLog("Exchange Rate (scaled up): ", exchangeRateMantissa);
console.log("Exchange Rate (scaled up): %s", exchangeRateMantissa);
//Amount added to your supply balance this block
uint256 supplyRateMantissa = cDAI.supplyRatePerBlock();
emit MyLog("Supply Rate (scaled up): ", supplyRateMantissa);
console.log("Supply Rate (scaled up): %s", supplyRateMantissa);
//Approve transfer on the DAI contract
daiToken.approve(cDAIAddress, amount);
uint256 myBefore = mycDAIbalance();
// Mint cTokens
uint256 mintResult = cDAI.mint(amount);
uint256 myAfter = mycDAIbalance();
addressToCmp[player].owner = player;
addressToCmp[player].isStaking = true;
addressToCmp[player].maturation = maturationTimestamp;
addressToCmp[player].cDAIAmount = myAfter - myBefore;
addressToStakeType[player] = stakeType;
emit Stake2(addressToCmp[player]);
return mintResult;
}
function redeemDAIFrom88mph(address player) private {
require(
addressToMph[player].isStaking,
"La Vie: Not currently staking!"
);
require(
block.timestamp >= addressToMph[player].maturation,
"La Vie: Too early to unstake"
);
require(
addressToMph[player].owner == player,
"La Vie: You dont own this stake!"
);
require(addressToMph[player].mphID != 0, "depositID not set");
uint64 depositID = addressToMph[player].mphID;
console.log("depositID: %s", depositID);
if (addressToMph[player].vestID != 0) {
uint64 vestID = addressToMph[player].vestID;
console.log("vestID: %s", vestID);
uint256 rewards = vesting.withdraw(vestID);
console.log(rewards);
Mph.transfer(player, rewards);
}
uint256 virtualTokenAmount = type(uint256).max; // withdraw all funds
bool early = false; // withdrawing after maturation
uint256 amount = pool.withdraw(depositID, virtualTokenAmount, early);
daiToken.transfer(player, amount);
addressToMph[player].owner = address(0);
addressToMph[player].isStaking = false;
addressToMph[player].maturation = 0;
addressToMph[player].mphID = 0;
addressToMph[player].vestID = 0;
addressToStakeType[player] = 0;
emit Unstake(player, amount);
}
function redeemDAIFromCMP(address player) private {
require(
addressToCmp[player].isStaking,
"La Vie: Not currently staking!"
);
require(
block.timestamp >= addressToCmp[player].maturation,
"La Vie: Too early to unstake"
);
require(
addressToCmp[player].owner == player,
"La Vie: You dont own this stake!"
);
uint256 redeemResult;
uint256 myDaiBefore = daiToken.balanceOf(address(this));
uint256 cDAIamount = addressToCmp[player].cDAIAmount;
redeemResult = cDAI.redeem(cDAIamount);
uint256 myDaiAfter = daiToken.balanceOf(address(this));
emit MyLog("If this is not 0, there was an error", redeemResult);
require(redeemResult == 0, "redeemResult error");
console.log("redeemResult: %s", redeemResult);
uint256 difference = myDaiAfter - myDaiBefore;
daiToken.transfer(player, difference);
addressToCmp[player].owner = address(0);
addressToCmp[player].isStaking = false;
addressToCmp[player].maturation = 0;
addressToCmp[player].cDAIAmount = 0;
addressToStakeType[player] = 0;
emit Unstake(player, addressToCmp[player].cDAIAmount);
}
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
function setVestID(address player, uint64 vestID) external onlyOwner {
require(
addressToMph[player].owner == player,
"La Vie: You dont own this stake!"
);
require(
addressToMph[player].vestID == 0,
"La Vie: vestID already set!"
);
require(
addressToMph[player].mphID != 0,
"La Vie: No deposit for this account!"
);
addressToMph[player].vestID = vestID;
}
function getVestID(address addr, uint64 depositID)
public
view
returns (uint64 vestingID)
{
return depositIDToVestID[addr][depositID];
}
function getStakedAmount(address player) external view returns (uint256) {
require(
addressToStakeType[player] != 0,
"La Vie: Not currently staking!"
);
if (addressToStakeType[player] == 1) {
return addressToMph[player].stakedAmount;
} else if (addressToStakeType[player] == 2) {
return addressToCmp[player].cDAIAmount;
}
return 0;
}
function getMaturation(address player) external view returns (uint64) {
return addressToMph[player].maturation;
}
function isStakingBool(address player) external view returns (bool) {
require(
addressToStakeType[player] != 0,
"La Vie: Not currently staking!"
);
if (addressToStakeType[player] == 1) {
return addressToMph[player].isStaking;
} else if (addressToStakeType[player] == 2) {
return addressToCmp[player].isStaking;
}
return false;
}
function mycDAIbalance() public view returns (uint256) {
return cDAI.balanceOf(address(this));
}
function increaseCash(address player, uint256 amount) external onlyOwner {
LaVxToken.transfer(player, amount);
}
function setAccountType(address player, uint8 accountType)
external
onlyOwner
{
addressToAccountType[player] = accountType;
}
function getAccountType(address player) external view returns (uint8) {
return addressToAccountType[player];
}
receive() external payable {}
}
| 0 laVieImage uint64 vestingID = vesting.getVestID(player, depositID); console.log("vesting ID: %s",vestingID); addressToMph[player].vestID = vestingID; addressToMph[player].vestID, | function supplyDAITo88MPH(
address player,
uint256 amount,
uint256 timeInDays,
uint8 stakeType
) private {
require(!(addressToMph[player].isStaking), "La Vie: Already staking!");
uint64 maturationTimestamp = uint64(
block.timestamp + (timeInDays * 1 days)
);
console.log(maturationTimestamp);
require(daiToken.approve(address(pool), amount));
console.log("approved");
(uint64 depositID, ) = pool.deposit(
amount,
maturationTimestamp
);
console.log(depositID);
console.log("mph deposit");
addressToMph[player].owner = player;
addressToMph[player].isStaking = true;
addressToMph[player].maturation = maturationTimestamp;
addressToMph[player].mphID = depositID;
addressToMph[player].stakedAmount = amount;
console.log(
"Mph struct of ID: %s with maturation of %s",
addressToMph[player].mphID,
addressToMph[player].maturation
);
console.log("depositID for %s : %s ", player, depositID);
addressToStakeType[player] = stakeType;
emit Stake1(addressToMph[msg.sender]);
}
| 921,499 | [
1,
20,
7125,
58,
1385,
2040,
225,
2254,
1105,
331,
10100,
734,
273,
331,
10100,
18,
588,
58,
395,
734,
12,
14872,
16,
443,
1724,
734,
1769,
225,
2983,
18,
1330,
2932,
90,
10100,
1599,
30,
738,
87,
3113,
90,
10100,
734,
1769,
1758,
774,
49,
844,
63,
14872,
8009,
26923,
734,
273,
331,
10100,
734,
31,
1758,
774,
49,
844,
63,
14872,
8009,
26923,
734,
16,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
14467,
9793,
45,
774,
5482,
4566,
44,
12,
203,
3639,
1758,
7291,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
2254,
5034,
813,
382,
9384,
16,
203,
3639,
2254,
28,
384,
911,
559,
203,
565,
262,
3238,
288,
203,
3639,
2583,
12,
5,
12,
2867,
774,
49,
844,
63,
14872,
8009,
291,
510,
6159,
3631,
315,
30745,
776,
1385,
30,
17009,
384,
6159,
4442,
1769,
203,
203,
3639,
2254,
1105,
4834,
872,
4921,
273,
2254,
1105,
12,
203,
5411,
1203,
18,
5508,
397,
261,
957,
382,
9384,
380,
404,
4681,
13,
203,
3639,
11272,
203,
3639,
2983,
18,
1330,
12,
7373,
872,
4921,
1769,
203,
3639,
2583,
12,
2414,
77,
1345,
18,
12908,
537,
12,
2867,
12,
6011,
3631,
3844,
10019,
203,
3639,
2983,
18,
1330,
2932,
25990,
8863,
203,
3639,
261,
11890,
1105,
443,
1724,
734,
16,
262,
273,
2845,
18,
323,
1724,
12,
203,
5411,
3844,
16,
203,
5411,
4834,
872,
4921,
203,
3639,
11272,
203,
203,
3639,
2983,
18,
1330,
12,
323,
1724,
734,
1769,
203,
203,
3639,
2983,
18,
1330,
2932,
81,
844,
443,
1724,
8863,
203,
203,
203,
203,
3639,
1758,
774,
49,
844,
63,
14872,
8009,
8443,
273,
7291,
31,
203,
3639,
1758,
774,
49,
844,
63,
14872,
8009,
291,
510,
6159,
273,
638,
31,
203,
3639,
1758,
774,
49,
844,
63,
14872,
8009,
7373,
872,
273,
4834,
872,
4921,
31,
203,
3639,
1758,
774,
49,
844,
63,
14872,
8009,
81,
844,
734,
273,
443,
1724,
734,
31,
203,
3639,
1758,
774,
49,
844,
63,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-05-02
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
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);
}
interface IAaveEcosystemReserveController {
/**
* @notice Proxy function for ERC20's approve(), pointing to a specific collector contract
* @param collector The collector contract with funds (Aave ecosystem reserve)
* @param token The asset address
* @param recipient Allowance's recipient
* @param amount Allowance to approve
**/
function approve(
address collector,
IERC20 token,
address recipient,
uint256 amount
) external;
/**
* @notice Proxy function for ERC20's transfer(), pointing to a specific collector contract
* @param collector The collector contract with funds (Aave ecosystem reserve)
* @param token The asset address
* @param recipient Transfer's recipient
* @param amount Amount to transfer
**/
function transfer(
address collector,
IERC20 token,
address recipient,
uint256 amount
) external;
/**
* @notice Proxy function to create a stream of token on a specific collector contract
* @param collector The collector contract with funds (Aave ecosystem reserve)
* @param recipient The recipient of the stream of token
* @param deposit Total amount to be streamed
* @param tokenAddress The ERC20 token to use as streaming asset
* @param startTime The unix timestamp for when the stream starts
* @param stopTime The unix timestamp for when the stream stops
* @return uint256 The stream id created
**/
function createStream(
address collector,
address recipient,
uint256 deposit,
IERC20 tokenAddress,
uint256 startTime,
uint256 stopTime
) external returns (uint256);
/**
* @notice Proxy function to withdraw from a stream of token on a specific collector contract
* @param collector The collector contract with funds (Aave ecosystem reserve)
* @param streamId The id of the stream to withdraw tokens from
* @param funds Amount to withdraw
* @return bool If the withdrawal finished properly
**/
function withdrawFromStream(
address collector,
uint256 streamId,
uint256 funds
) external returns (bool);
/**
* @notice Proxy function to cancel a stream of token on a specific collector contract
* @param collector The collector contract with funds (Aave ecosystem reserve)
* @param streamId The id of the stream to cancel
* @return bool If the cancellation happened correctly
**/
function cancelStream(address collector, uint256 streamId)
external
returns (bool);
}
interface IStreamable {
struct Stream {
uint256 deposit;
uint256 ratePerSecond;
uint256 remainingBalance;
uint256 startTime;
uint256 stopTime;
address recipient;
address sender;
address tokenAddress;
bool isEntity;
}
event CreateStream(
uint256 indexed streamId,
address indexed sender,
address indexed recipient,
uint256 deposit,
address tokenAddress,
uint256 startTime,
uint256 stopTime
);
event WithdrawFromStream(
uint256 indexed streamId,
address indexed recipient,
uint256 amount
);
event CancelStream(
uint256 indexed streamId,
address indexed sender,
address indexed recipient,
uint256 senderBalance,
uint256 recipientBalance
);
function balanceOf(uint256 streamId, address who)
external
view
returns (uint256 balance);
function getStream(uint256 streamId)
external
view
returns (
address sender,
address recipient,
uint256 deposit,
address token,
uint256 startTime,
uint256 stopTime,
uint256 remainingBalance,
uint256 ratePerSecond
);
function createStream(
address recipient,
uint256 deposit,
address tokenAddress,
uint256 startTime,
uint256 stopTime
) external returns (uint256 streamId);
function withdrawFromStream(uint256 streamId, uint256 funds)
external
returns (bool);
function cancelStream(uint256 streamId) external returns (bool);
function initialize(address fundsAdmin) external;
}
interface IInitializableAdminUpgradeabilityProxy {
function upgradeTo(address newImplementation) external;
function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable;
function admin() external returns (address);
function implementation() external returns (address);
}
interface IAdminControlledEcosystemReserve {
/** @notice Emitted when the funds admin changes
* @param fundsAdmin The new funds admin
**/
event NewFundsAdmin(address indexed fundsAdmin);
/** @notice Returns the mock ETH reference address
* @return address The address
**/
function ETH_MOCK_ADDRESS() external pure returns (address);
/**
* @notice Return the funds admin, only entity to be able to interact with this contract (controller of reserve)
* @return address The address of the funds admin
**/
function getFundsAdmin() external view returns (address);
/**
* @dev Function for the funds admin to give ERC20 allowance to other parties
* @param token The address of the token to give allowance from
* @param recipient Allowance's recipient
* @param amount Allowance to approve
**/
function approve(
IERC20 token,
address recipient,
uint256 amount
) external;
/**
* @notice Function for the funds admin to transfer ERC20 tokens to other parties
* @param token The address of the token to transfer
* @param recipient Transfer's recipient
* @param amount Amount to transfer
**/
function transfer(
IERC20 token,
address recipient,
uint256 amount
) external;
}
contract PayloadAaveBGD {
IInitializableAdminUpgradeabilityProxy public constant COLLECTOR_V2_PROXY =
IInitializableAdminUpgradeabilityProxy(
0x464C71f6c2F760DdA6093dCB91C24c39e5d6e18c
);
IInitializableAdminUpgradeabilityProxy
public constant AAVE_TOKEN_COLLECTOR_PROXY =
IInitializableAdminUpgradeabilityProxy(
0x25F2226B597E8F9514B3F68F00f494cF4f286491
);
address public constant GOV_SHORT_EXECUTOR =
0xEE56e2B3D491590B5b31738cC34d5232F378a8D5;
IAaveEcosystemReserveController public constant CONTROLLER_OF_COLLECTOR =
IAaveEcosystemReserveController(
0x3d569673dAa0575c936c7c67c4E6AedA69CC630C
);
IStreamable public constant ECOSYSTEM_RESERVE_V2_IMPL =
IStreamable(0x1aa435ed226014407Fa6b889e9d06c02B1a12AF3);
IERC20 public constant AUSDC =
IERC20(0xBcca60bB61934080951369a648Fb03DF4F96263C);
IERC20 public constant ADAI =
IERC20(0x028171bCA77440897B824Ca71D1c56caC55b68A3);
IERC20 public constant AUSDT =
IERC20(0x3Ed3B47Dd13EC9a98b44e6204A523E766B225811);
IERC20 public constant AAVE =
IERC20(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9);
uint256 public constant AUSDC_UPFRONT_AMOUNT = 1200000 * 1e6; // 1'200'000 aUSDC
uint256 public constant ADAI_UPFRONT_AMOUNT = 1000000 ether; // 1'000'000 aDAI
uint256 public constant AUSDT_UPFRONT_AMOUNT = 1000000 * 1e6; // 1'000'000 aUSDT
uint256 public constant AAVE_UPFRONT_AMOUNT = 8400 ether; // 8'400 AAVE
uint256 public constant AUSDC_STREAM_AMOUNT = 4800008160000; // ~4'800'000 aUSDC. A bit more for the streaming requirements
uint256 public constant AAVE_STREAM_AMOUNT = 12600000000000074880000; // ~12'600 AAVE. A bit more for the streaming requirements
uint256 public constant STREAMS_DURATION = 450 days; // 15 months of 30 days
address public constant BGD_RECIPIENT =
0xb812d0944f8F581DfAA3a93Dda0d22EcEf51A9CF;
function execute() external {
// Upgrade of both treasuries' implementation
// We use a common implementation for both ecosystem's reserves
COLLECTOR_V2_PROXY.upgradeToAndCall(
address(ECOSYSTEM_RESERVE_V2_IMPL),
abi.encodeWithSelector(
IStreamable.initialize.selector,
address(CONTROLLER_OF_COLLECTOR)
)
);
AAVE_TOKEN_COLLECTOR_PROXY.upgradeToAndCall(
address(ECOSYSTEM_RESERVE_V2_IMPL),
abi.encodeWithSelector(
IStreamable.initialize.selector,
address(CONTROLLER_OF_COLLECTOR)
)
);
// We initialise the implementation, for security
ECOSYSTEM_RESERVE_V2_IMPL.initialize(address(CONTROLLER_OF_COLLECTOR));
// Transfer of the upfront payment, 40% of the total
CONTROLLER_OF_COLLECTOR.transfer(
address(COLLECTOR_V2_PROXY),
AUSDC,
BGD_RECIPIENT,
AUSDC_UPFRONT_AMOUNT
);
CONTROLLER_OF_COLLECTOR.transfer(
address(COLLECTOR_V2_PROXY),
ADAI,
BGD_RECIPIENT,
ADAI_UPFRONT_AMOUNT
);
CONTROLLER_OF_COLLECTOR.transfer(
address(COLLECTOR_V2_PROXY),
AUSDT,
BGD_RECIPIENT,
AUSDT_UPFRONT_AMOUNT
);
CONTROLLER_OF_COLLECTOR.transfer(
address(AAVE_TOKEN_COLLECTOR_PROXY),
AAVE,
BGD_RECIPIENT,
AAVE_UPFRONT_AMOUNT
);
// Creation of the streams
CONTROLLER_OF_COLLECTOR.createStream(
address(COLLECTOR_V2_PROXY),
BGD_RECIPIENT,
AUSDC_STREAM_AMOUNT,
AUSDC,
block.timestamp,
block.timestamp + STREAMS_DURATION
);
CONTROLLER_OF_COLLECTOR.createStream(
address(AAVE_TOKEN_COLLECTOR_PROXY),
BGD_RECIPIENT,
AAVE_STREAM_AMOUNT,
AAVE,
block.timestamp,
block.timestamp + STREAMS_DURATION
);
}
} | Upgrade of both treasuries' implementation We use a common implementation for both ecosystem's reserves We initialise the implementation, for security Transfer of the upfront payment, 40% of the total Creation of the streams | function balanceOf(uint256 streamId, address who)
external
view
returns (uint256 balance);
function getStream(uint256 streamId)
external
view
returns (
address sender,
address recipient,
uint256 deposit,
address token,
uint256 startTime,
uint256 stopTime,
uint256 remainingBalance,
uint256 ratePerSecond
);
function createStream(
address recipient,
uint256 deposit,
address tokenAddress,
uint256 startTime,
uint256 stopTime
) external returns (uint256 streamId);
function withdrawFromStream(uint256 streamId, uint256 funds)
external
returns (bool);
function cancelStream(uint256 streamId) external returns (bool);
function initialize(address fundsAdmin) external;
}
}
}
function execute() external {
COLLECTOR_V2_PROXY.upgradeToAndCall(
address(ECOSYSTEM_RESERVE_V2_IMPL),
abi.encodeWithSelector(
IStreamable.initialize.selector,
address(CONTROLLER_OF_COLLECTOR)
)
);
AAVE_TOKEN_COLLECTOR_PROXY.upgradeToAndCall(
address(ECOSYSTEM_RESERVE_V2_IMPL),
abi.encodeWithSelector(
IStreamable.initialize.selector,
address(CONTROLLER_OF_COLLECTOR)
)
);
ECOSYSTEM_RESERVE_V2_IMPL.initialize(address(CONTROLLER_OF_COLLECTOR));
CONTROLLER_OF_COLLECTOR.transfer(
address(COLLECTOR_V2_PROXY),
AUSDC,
BGD_RECIPIENT,
AUSDC_UPFRONT_AMOUNT
);
CONTROLLER_OF_COLLECTOR.transfer(
address(COLLECTOR_V2_PROXY),
ADAI,
BGD_RECIPIENT,
ADAI_UPFRONT_AMOUNT
);
CONTROLLER_OF_COLLECTOR.transfer(
address(COLLECTOR_V2_PROXY),
AUSDT,
BGD_RECIPIENT,
AUSDT_UPFRONT_AMOUNT
);
CONTROLLER_OF_COLLECTOR.transfer(
address(AAVE_TOKEN_COLLECTOR_PROXY),
AAVE,
BGD_RECIPIENT,
AAVE_UPFRONT_AMOUNT
);
CONTROLLER_OF_COLLECTOR.createStream(
address(COLLECTOR_V2_PROXY),
BGD_RECIPIENT,
AUSDC_STREAM_AMOUNT,
AUSDC,
block.timestamp,
block.timestamp + STREAMS_DURATION
);
CONTROLLER_OF_COLLECTOR.createStream(
address(AAVE_TOKEN_COLLECTOR_PROXY),
BGD_RECIPIENT,
AAVE_STREAM_AMOUNT,
AAVE,
block.timestamp,
block.timestamp + STREAMS_DURATION
);
}
| 15,035,499 | [
1,
10784,
434,
3937,
9787,
345,
295,
606,
11,
4471,
1660,
999,
279,
2975,
4471,
364,
3937,
6557,
538,
1108,
1807,
400,
264,
3324,
1660,
21301,
326,
4471,
16,
364,
4373,
12279,
434,
326,
731,
10211,
5184,
16,
8063,
9,
434,
326,
2078,
18199,
434,
326,
8205,
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,
445,
11013,
951,
12,
11890,
5034,
21035,
16,
1758,
10354,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
11013,
1769,
203,
203,
565,
445,
13741,
12,
11890,
5034,
21035,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
203,
5411,
1758,
5793,
16,
203,
5411,
1758,
8027,
16,
203,
5411,
2254,
5034,
443,
1724,
16,
203,
5411,
1758,
1147,
16,
203,
5411,
2254,
5034,
8657,
16,
203,
5411,
2254,
5034,
2132,
950,
16,
203,
5411,
2254,
5034,
4463,
13937,
16,
203,
5411,
2254,
5034,
4993,
2173,
8211,
203,
3639,
11272,
203,
203,
565,
445,
752,
1228,
12,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
443,
1724,
16,
203,
3639,
1758,
1147,
1887,
16,
203,
3639,
2254,
5034,
8657,
16,
203,
3639,
2254,
5034,
2132,
950,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
21035,
1769,
203,
203,
565,
445,
598,
9446,
1265,
1228,
12,
11890,
5034,
21035,
16,
2254,
5034,
284,
19156,
13,
203,
3639,
3903,
203,
3639,
1135,
261,
6430,
1769,
203,
203,
565,
445,
3755,
1228,
12,
11890,
5034,
21035,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
4046,
12,
2867,
284,
19156,
4446,
13,
3903,
31,
203,
97,
203,
97,
203,
97,
203,
203,
203,
565,
445,
1836,
1435,
3903,
288,
203,
3639,
5597,
3918,
916,
67,
58,
22,
67,
16085,
18,
15097,
774,
1876,
1477,
12,
203,
5411,
1758,
12,
41,
3865,
14318,
67,
862,
2123,
3412,
67,
58,
22,
67,
3445,
6253,
3631,
203,
5411,
24126,
18,
2
] |
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <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/IERC721.sol
pragma solidity >=0.6.2 <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/IERC721Metadata.sol
pragma solidity >=0.6.2 <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/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @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);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <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/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// 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/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/utils/EnumerableSet.sol
pragma solidity >=0.6.0 <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;
// 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];
}
// 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);
}
// 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))));
}
// 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/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` 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);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// 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;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @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 _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @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 || ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(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); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(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"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @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()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <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 () internal {
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;
}
}
pragma solidity ^0.7.0;
/**
* @title BitMates contract
* https://bitmates.io
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract BitMates is ERC721, Ownable {
using SafeMath for uint256;
string public BitMatesRecord = "";
uint256 public constant bitMatePrice = 70000000000000000; //0.07 ETH
uint public constant maxApePurchase = 20;
uint256 public maxBitMates;
bool public saleIsActive = false;
// addresses
// founder address
address t1 = 0x2ae929FD768bE055d5B39eb8140F5Ba537362fC8;
address t2 = 0xCe43925a55c876e7904C3ea262b29Eecd0D0109b;
//BitMates multisig
address t3 = 0x44513A31cA10750F1FF4B7bDAf00591c183802a2;
constructor(string memory name, string memory symbol, uint256 maxNftSupply) ERC721(name, symbol) {
maxBitMates = maxNftSupply;
// Setting the first 2 BitMates
_safeMint( t2, 0);
_safeMint( t1, 1);
}
/*
Withdrawing the funds from the contract
*/
function withdrawAll() public payable onlyOwner {
uint256 _each = address(this).balance;
require(payable(t3).send(_each));
}
/*
* Set some BitMates aside
*/
function reserveApes(uint numberOfTokens) public onlyOwner {
require(totalSupply().add(numberOfTokens) <= maxBitMates, "Purchase would exceed max supply of BitMates");
for (uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < maxBitMates) {
_safeMint(msg.sender, mintIndex);
}
}
}
/*
* Set IPFS pointer after conclusion of sale
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
BitMatesRecord = provenanceHash;
}
/*
Sets the pointer for the metadata
*/
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
/*
* Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/*
* Mints BitMates
*/
function mintApe(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint BitMate");
require(numberOfTokens <= maxApePurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= maxBitMates, "Purchase would exceed max supply of BitMates");
require(bitMatePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < maxBitMates) {
_safeMint(msg.sender, mintIndex);
}
}
}
/*
Allows calldata to be used to store metadata on-chain
Credits to @0xmons // for more info: https://blog.0xmons.xyz/79081566310
*/
function uploadBitMateImage(bytes calldata s) external onlyOwner {}
/*
Allows calldata to be used to store metadata on-chain
Credits to @0xmons // for more info: https://blog.0xmons.xyz/79081566310
*/
function uploadBitMateAttributes(bytes calldata s) external onlyOwner {}
} | * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. Requirements: - `tokenId` must exist./ | function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
| 1,481,593 | [
1,
2785,
1375,
67,
2316,
3098,
68,
487,
326,
1147,
3098,
434,
1375,
2316,
548,
8338,
29076,
30,
300,
1375,
2316,
548,
68,
1297,
1005,
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
] | [
1,
1,
1,
1,
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,
565,
445,
389,
542,
1345,
3098,
12,
11890,
5034,
1147,
548,
16,
533,
3778,
389,
2316,
3098,
13,
2713,
5024,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
654,
39,
27,
5340,
2277,
30,
3699,
444,
434,
1661,
19041,
1147,
8863,
203,
540,
203,
3639,
389,
2316,
1099,
2520,
63,
2316,
548,
65,
273,
389,
2316,
3098,
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
] |
pragma solidity >=0.8.0 <0.9.0;
//SPDX-License-Identifier: MIT
import "hardhat/console.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./AuthorEntity.sol";
import "./ArticleEntity.sol";
/// @dev TDAO token interface
interface ITDAOToken {
function mintTokens(uint256 amount, address to) external;
function transfer ( address recipient, uint256 amount ) external returns ( bool );
function transferFrom ( address sender, address recipient, uint256 amount ) external returns ( bool );
function approve ( address spender, uint256 amount ) external returns ( bool );
function burnTokens(uint256 amount, address from) external;
function balanceOf ( address account ) external view returns ( uint256 );
}
interface ITDAONFTToken {
function mintNFTForArticle(address ownerAddress, string memory metadataPtr, uint256 amount) external returns(uint256);
}
interface ITDAOMemberToken{
function mintMembershipToken(address authorAddress, string memory metadataPtr, uint256 amount) external returns(uint256);
}
/// @title TokenRecover
/// @author jaxcoder
/// @dev Allow to recover any ERC20 sent into the contract for error
contract TokenRecover is Ownable {
/**
* @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 onlyOwner {
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
}
/// @title Manages the Authors and Articles on-chain
/// @author jaxcoder
/// @notice
/// @dev
contract TalentDaoManager is Ownable, AuthorEntity, AccessControl, TokenRecover {
using SafeERC20 for IERC20;
using SafeMath for uint256;
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
address public manager;
ITDAOToken public tDaoToken;
address public tDaoTokenAddress;
ITDAONFTToken public tDaoNftToken;
ITDAOMemberToken public tDaoMemberToken;
event ManagerRemoved(address indexed oldManager);
event ManagerAdded(address indexed newManager);
constructor(address _manager, address _owner, address _TDAOToken, address _TDAONFTToken, address _TDAOMemberToken) public {
manager = _manager;
_setupRole(MANAGER_ROLE, _manager);
tDaoToken = ITDAOToken(_TDAOToken);
tDaoTokenAddress = _TDAOToken;
tDaoNftToken = ITDAONFTToken(_TDAONFTToken);
tDaoMemberToken = ITDAOMemberToken(_TDAOMemberToken);
transferOwnership(_owner);
}
function mintMemberToken (address to, string memory metadataPtr, uint256 amount) public {
tDaoMemberToken.mintMembershipToken(to, metadataPtr, amount);
}
/// @dev transfer TDAO tokens
/// @param to the recipient of the tokens
function _transferTokens (address to, uint256 amount) internal {
tDaoToken.transfer(to, amount);
}
/// @dev transfer TDAO tokens
/// @param from the sender(author) of the tokens
function transferTokens (address from, uint256 amount) public onlyRole(MANAGER_ROLE) {
tDaoToken.transferFrom(from, address(this), amount);
}
/// @dev admin function to update the contract manager
/// @param newManager the address of the new manager
function updateManger (address newManager) public onlyOwner {
revokeRole(MANAGER_ROLE, manager);
emit ManagerRemoved(manager);
manager = newManager;
grantRole(MANAGER_ROLE, manager);
emit ManagerAdded(manager);
}
function mintArticleNFT(address owner, string memory metadataPtr, uint256 amount)
public
returns (uint256)
{
(uint256 newItemId) = tDaoNftToken.mintNFTForArticle(owner, metadataPtr, amount);
return (newItemId);
}
function tipAuthor(address author, uint256 amount) public {
console.log(amount);
require(tDaoToken.balanceOf(msg.sender) >= amount, "You don't have enough TDAO tokens");
tDaoToken.transferFrom(msg.sender, author, amount);
}
} | @title TokenRecover @author jaxcoder @dev Allow to recover any ERC20 sent into the contract for error | contract TokenRecover is Ownable {
function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner {
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
}
| 12,677,855 | [
1,
1345,
27622,
225,
20516,
3396,
225,
7852,
358,
5910,
1281,
4232,
39,
3462,
3271,
1368,
326,
6835,
364,
555,
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
] | [
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,
0
] | [
1,
16351,
3155,
27622,
353,
14223,
6914,
288,
203,
565,
445,
5910,
654,
39,
3462,
12,
2867,
1147,
1887,
16,
2254,
5034,
1147,
6275,
13,
1071,
1338,
5541,
288,
203,
3639,
467,
654,
39,
3462,
12,
2316,
1887,
2934,
13866,
12,
8443,
9334,
1147,
6275,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-2021 StarkWare Industries 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
https://www.starkware.co/open-source-license/
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-2.0.
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "./interfaces/IFactRegistry.sol";
import "./interfaces/IIdentity.sol";
import "./libraries/Output.sol";
import "./components/StarknetGovernance.sol";
import "./components/StarknetMessaging.sol";
import "./components/StarknetOperator.sol";
import "./libraries/StarknetState.sol";
import "./libraries/NamedStorage.sol";
import "./interfaces/ContractInitializer.sol";
import "./components/ProxySupport.sol";
import "./libraries/OnchainDataFactTreeEncoder.sol";
import "./interfaces/GovernedFinalizable.sol";
contract Starknet is
IIdentity,
StarknetMessaging,
StarknetGovernance,
GovernedFinalizable,
StarknetOperator,
ContractInitializer,
ProxySupport
{
using StarknetState for StarknetState.State;
// Logs the new state following a state update.
event LogStateUpdate(uint256 globalRoot, int256 sequenceNumber);
// Logs a stateTransitionFact that was used to update the state.
event LogStateTransitionFact(bytes32 stateTransitionFact);
// Random storage slot tags.
string internal constant PROGRAM_HASH_TAG = "STARKNET_1.0_INIT_PROGRAM_HASH_UINT";
string internal constant VERIFIER_ADDRESS_TAG = "STARKNET_1.0_INIT_VERIFIER_ADDRESS";
string internal constant STATE_STRUCT_TAG = "STARKNET_1.0_INIT_STARKNET_STATE_STRUCT";
function setProgramHash(uint256 newProgramHash) external notFinalized onlyGovernance {
programHash(newProgramHash);
}
// State variable "programHash" read-access functions.
function programHash() public view returns (uint256) {
return NamedStorage.getUintValue(PROGRAM_HASH_TAG);
}
// State variable "programHash" write-access functions.
function programHash(uint256 value) internal {
NamedStorage.setUintValue(PROGRAM_HASH_TAG, value);
}
// State variable "verifier" access functions.
function verifier() internal view returns (address) {
return NamedStorage.getAddressValue(VERIFIER_ADDRESS_TAG);
}
function setVerifierAddress(address value) internal {
NamedStorage.setAddressValueOnce(VERIFIER_ADDRESS_TAG, value);
}
// State variable "state" access functions.
function state() internal pure returns (StarknetState.State storage stateStruct) {
bytes32 location = keccak256(abi.encodePacked(STATE_STRUCT_TAG));
assembly {
stateStruct_slot := location
}
}
function isInitialized() internal view override returns (bool) {
return programHash() != 0;
}
function numOfSubContracts() internal pure override returns (uint256) {
return 0;
}
function validateInitData(bytes calldata data) internal pure override {
require(data.length == 4 * 32, "ILLEGAL_INIT_DATA_SIZE");
uint256 programHash_ = abi.decode(data[:32], (uint256));
require(programHash_ != 0, "BAD_INITIALIZATION");
}
function processSubContractAddresses(bytes calldata subContractAddresses) internal override {}
function initializeContractState(bytes calldata data) internal override {
(uint256 programHash_, address verifier_, StarknetState.State memory initialState) = abi.decode(
data,
(uint256, address, StarknetState.State)
);
programHash(programHash_);
setVerifierAddress(verifier_);
state().copy(initialState);
}
/**
Returns a string that identifies the contract.
*/
function identify() external pure override returns (string memory) {
return "StarkWare_Starknet_2021_1";
}
/**
Returns the current state root.
*/
function stateRoot() external view returns (uint256) {
return state().globalRoot;
}
/**
Returns the current sequence number.
*/
function stateSequenceNumber() external view returns (int256) {
return state().sequenceNumber;
}
/**
Updates the state of the StarkNet, based on a proof of the
StarkNet OS that the state transition is valid.
Arguments:
sequenceNumber - The expected sequence number of the new block.
programOutput - The main part of the StarkNet OS program output.
data_availability_fact - An encoding of the on-chain data associated
with the 'programOutput'.
*/
function updateState(
int256 sequenceNumber,
uint256[] calldata programOutput,
uint256 onchainDataHash,
uint256 onchainDataSize
) external onlyOperator {
// Validate program output.
StarknetOutput.validate(programOutput);
bytes32 stateTransitionFact = OnchainDataFactTreeEncoder.encodeFactWithOnchainData(
programOutput,
OnchainDataFactTreeEncoder.DataAvailabilityFact(onchainDataHash, onchainDataSize)
);
bytes32 sharpFact = keccak256(abi.encode(programHash(), stateTransitionFact));
require(IFactRegistry(verifier()).isValid(sharpFact), "NO_STATE_TRANSITION_PROOF");
emit LogStateTransitionFact(stateTransitionFact);
// Process L2 -> L1 messages.
uint256 outputOffset = StarknetOutput.HEADER_SIZE;
outputOffset += StarknetOutput.processMessages(
// isL2ToL1=
true,
programOutput[outputOffset:],
l2ToL1Messages()
);
// Process L1 -> L2 messages.
outputOffset += StarknetOutput.processMessages(
// isL2ToL1=
false,
programOutput[outputOffset:],
l1ToL2Messages()
);
require(outputOffset == programOutput.length, "STARKNET_OUTPUT_TOO_LONG");
// Perform state update.
state().update(sequenceNumber, programOutput);
StarknetState.State memory state_ = state();
emit LogStateUpdate(state_.globalRoot, state_.sequenceNumber);
}
}
| Logs the new state following a state update. Logs a stateTransitionFact that was used to update the state. Random storage slot tags. | {
using StarknetState for StarknetState.State;
event LogStateUpdate(uint256 globalRoot, int256 sequenceNumber);
event LogStateTransitionFact(bytes32 stateTransitionFact);
string internal constant PROGRAM_HASH_TAG = "STARKNET_1.0_INIT_PROGRAM_HASH_UINT";
string internal constant VERIFIER_ADDRESS_TAG = "STARKNET_1.0_INIT_VERIFIER_ADDRESS";
string internal constant STATE_STRUCT_TAG = "STARKNET_1.0_INIT_STARKNET_STATE_STRUCT";
Copyright 2019-2021 StarkWare Industries Ltd.
pragma solidity ^0.6.12;
function setProgramHash(uint256 newProgramHash) external notFinalized onlyGovernance {
programHash(newProgramHash);
}
function programHash() public view returns (uint256) {
return NamedStorage.getUintValue(PROGRAM_HASH_TAG);
}
function programHash(uint256 value) internal {
NamedStorage.setUintValue(PROGRAM_HASH_TAG, value);
}
function verifier() internal view returns (address) {
return NamedStorage.getAddressValue(VERIFIER_ADDRESS_TAG);
}
function setVerifierAddress(address value) internal {
NamedStorage.setAddressValueOnce(VERIFIER_ADDRESS_TAG, value);
}
function state() internal pure returns (StarknetState.State storage stateStruct) {
bytes32 location = keccak256(abi.encodePacked(STATE_STRUCT_TAG));
assembly {
stateStruct_slot := location
}
}
function state() internal pure returns (StarknetState.State storage stateStruct) {
bytes32 location = keccak256(abi.encodePacked(STATE_STRUCT_TAG));
assembly {
stateStruct_slot := location
}
}
function isInitialized() internal view override returns (bool) {
return programHash() != 0;
}
function numOfSubContracts() internal pure override returns (uint256) {
return 0;
}
function validateInitData(bytes calldata data) internal pure override {
require(data.length == 4 * 32, "ILLEGAL_INIT_DATA_SIZE");
uint256 programHash_ = abi.decode(data[:32], (uint256));
require(programHash_ != 0, "BAD_INITIALIZATION");
}
function processSubContractAddresses(bytes calldata subContractAddresses) internal override {}
function initializeContractState(bytes calldata data) internal override {
(uint256 programHash_, address verifier_, StarknetState.State memory initialState) = abi.decode(
data,
(uint256, address, StarknetState.State)
);
programHash(programHash_);
setVerifierAddress(verifier_);
state().copy(initialState);
}
Returns a string that identifies the contract.
function identify() external pure override returns (string memory) {
return "StarkWare_Starknet_2021_1";
}
Returns the current state root.
function stateRoot() external view returns (uint256) {
return state().globalRoot;
}
Returns the current sequence number.
function stateSequenceNumber() external view returns (int256) {
return state().sequenceNumber;
}
StarkNet OS that the state transition is valid.
Arguments:
sequenceNumber - The expected sequence number of the new block.
programOutput - The main part of the StarkNet OS program output.
data_availability_fact - An encoding of the on-chain data associated
with the 'programOutput'.
Updates the state of the StarkNet, based on a proof of the
function updateState(
int256 sequenceNumber,
uint256[] calldata programOutput,
uint256 onchainDataHash,
uint256 onchainDataSize
) external onlyOperator {
StarknetOutput.validate(programOutput);
bytes32 stateTransitionFact = OnchainDataFactTreeEncoder.encodeFactWithOnchainData(
programOutput,
OnchainDataFactTreeEncoder.DataAvailabilityFact(onchainDataHash, onchainDataSize)
);
bytes32 sharpFact = keccak256(abi.encode(programHash(), stateTransitionFact));
require(IFactRegistry(verifier()).isValid(sharpFact), "NO_STATE_TRANSITION_PROOF");
emit LogStateTransitionFact(stateTransitionFact);
uint256 outputOffset = StarknetOutput.HEADER_SIZE;
outputOffset += StarknetOutput.processMessages(
true,
programOutput[outputOffset:],
l2ToL1Messages()
);
outputOffset += StarknetOutput.processMessages(
false,
programOutput[outputOffset:],
l1ToL2Messages()
);
require(outputOffset == programOutput.length, "STARKNET_OUTPUT_TOO_LONG");
state().update(sequenceNumber, programOutput);
StarknetState.State memory state_ = state();
emit LogStateUpdate(state_.globalRoot, state_.sequenceNumber);
}
}
| 5,363,404 | [
1,
7777,
326,
394,
919,
3751,
279,
919,
1089,
18,
20238,
279,
919,
8850,
9766,
716,
1703,
1399,
358,
1089,
326,
919,
18,
8072,
2502,
4694,
2342,
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
] | [
1,
1,
1,
1,
1,
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
] | [
1,
95,
203,
565,
1450,
934,
1313,
2758,
1119,
364,
934,
1313,
2758,
1119,
18,
1119,
31,
203,
203,
565,
871,
1827,
1119,
1891,
12,
11890,
5034,
2552,
2375,
16,
509,
5034,
3102,
1854,
1769,
203,
203,
565,
871,
1827,
1119,
8850,
9766,
12,
3890,
1578,
919,
8850,
9766,
1769,
203,
203,
565,
533,
2713,
5381,
4629,
15370,
67,
15920,
67,
7927,
273,
315,
882,
9584,
14843,
67,
21,
18,
20,
67,
12919,
67,
21418,
67,
15920,
67,
57,
3217,
14432,
203,
565,
533,
2713,
5381,
6422,
10591,
67,
15140,
67,
7927,
273,
315,
882,
9584,
14843,
67,
21,
18,
20,
67,
12919,
67,
2204,
10591,
67,
15140,
14432,
203,
565,
533,
2713,
5381,
7442,
67,
13915,
67,
7927,
273,
315,
882,
9584,
14843,
67,
21,
18,
20,
67,
12919,
67,
882,
9584,
14843,
67,
7998,
67,
13915,
14432,
203,
203,
225,
25417,
30562,
17,
18212,
21,
934,
1313,
59,
834,
9223,
407,
2007,
511,
4465,
18,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
2138,
31,
203,
565,
445,
444,
9459,
2310,
12,
11890,
5034,
394,
9459,
2310,
13,
3903,
486,
7951,
1235,
1338,
43,
1643,
82,
1359,
288,
203,
3639,
5402,
2310,
12,
2704,
9459,
2310,
1769,
203,
565,
289,
203,
203,
565,
445,
5402,
2310,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
9796,
3245,
18,
588,
5487,
620,
12,
21418,
67,
15920,
67,
7927,
1769,
203,
565,
289,
203,
203,
565,
445,
5402,
2310,
12,
11890,
5034,
460,
13,
2713,
288,
203,
3639,
9796,
3245,
2
] |
// Copyright (C) 2021 BITFISH LIMITED
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.4;
import "./interfaces/IStakefishServicesContract.sol";
import "./interfaces/IStakefishServicesContractFactory.sol";
import "./libraries/ProxyFactory.sol";
import "./libraries/Address.sol";
import "./StakefishServicesContract.sol";
contract StakefishServicesContractFactory is ProxyFactory, IStakefishServicesContractFactory {
using Address for address;
using Address for address payable;
uint256 private constant FULL_DEPOSIT_SIZE = 32 ether;
uint256 private constant COMMISSION_RATE_SCALE = 1000000;
uint256 private _minimumDeposit = 0.1 ether;
address payable private _servicesContractImpl;
address private _operatorAddress;
uint24 private _commissionRate;
modifier onlyOperator() {
require(msg.sender == _operatorAddress);
_;
}
constructor(uint24 commissionRate)
{
require(uint256(commissionRate) <= COMMISSION_RATE_SCALE, "Commission rate exceeds scale");
_operatorAddress = msg.sender;
_commissionRate = commissionRate;
_servicesContractImpl = payable(new StakefishServicesContract());
StakefishServicesContract(_servicesContractImpl).initialize(0, address(0), "");
emit OperatorChanged(msg.sender);
emit CommissionRateChanged(commissionRate);
}
function changeOperatorAddress(address newAddress)
external
override
onlyOperator
{
require(newAddress != address(0), "Address can't be zero address");
_operatorAddress = newAddress;
emit OperatorChanged(newAddress);
}
function changeCommissionRate(uint24 newCommissionRate)
external
override
onlyOperator
{
require(uint256(newCommissionRate) <= COMMISSION_RATE_SCALE, "Commission rate exceeds scale");
_commissionRate = newCommissionRate;
emit CommissionRateChanged(newCommissionRate);
}
function changeMinimumDeposit(uint256 newMinimumDeposit)
external
override
onlyOperator
{
_minimumDeposit = newMinimumDeposit;
emit MinimumDepositChanged(newMinimumDeposit);
}
function createContract(
bytes32 saltValue,
bytes32 operatorDataCommitment
)
external
payable
override
returns (address)
{
require (msg.value <= 32 ether);
bytes memory initData =
abi.encodeWithSignature(
"initialize(uint24,address,bytes32)",
_commissionRate,
_operatorAddress,
operatorDataCommitment
);
address proxy = _createProxyDeterministic(_servicesContractImpl, initData, saltValue);
emit ContractCreated(saltValue);
if (msg.value > 0) {
IStakefishServicesContract(payable(proxy)).depositOnBehalfOf{value: msg.value}(msg.sender);
}
return proxy;
}
function createMultipleContracts(
uint256 baseSaltValue,
bytes32[] calldata operatorDataCommitments
)
external
payable
override
{
uint256 remaining = msg.value;
for (uint256 i = 0; i < operatorDataCommitments.length; i++) {
bytes32 salt = bytes32(baseSaltValue + i);
bytes memory initData =
abi.encodeWithSignature(
"initialize(uint24,address,bytes32)",
_commissionRate,
_operatorAddress,
operatorDataCommitments[i]
);
address proxy = _createProxyDeterministic(
_servicesContractImpl,
initData,
salt
);
emit ContractCreated(salt);
uint256 depositSize = _min(remaining, FULL_DEPOSIT_SIZE);
if (depositSize > 0) {
IStakefishServicesContract(payable(proxy)).depositOnBehalfOf{value: depositSize}(msg.sender);
remaining -= depositSize;
}
}
if (remaining > 0) {
payable(msg.sender).sendValue(remaining);
}
}
function fundMultipleContracts(
bytes32[] calldata saltValues,
bool force
)
external
payable
override
returns (uint256)
{
uint256 remaining = msg.value;
address depositor = msg.sender;
for (uint256 i = 0; i < saltValues.length; i++) {
if (!force && remaining < _minimumDeposit)
break;
address proxy = _getDeterministicAddress(_servicesContractImpl, saltValues[i]);
if (proxy.isContract()) {
IStakefishServicesContract sc = IStakefishServicesContract(payable(proxy));
if (sc.getState() == IStakefishServicesContract.State.PreDeposit) {
uint256 depositAmount = _min(remaining, FULL_DEPOSIT_SIZE - address(sc).balance);
if (force || depositAmount >= _minimumDeposit) {
sc.depositOnBehalfOf{value: depositAmount}(depositor);
remaining -= depositAmount;
}
}
}
}
if (remaining > 0) {
payable(msg.sender).sendValue(remaining);
}
return remaining;
}
function getOperatorAddress()
external
view
override
returns (address)
{
return _operatorAddress;
}
function getCommissionRate()
external
view
override
returns (uint24)
{
return _commissionRate;
}
function getServicesContractImpl()
external
view
override
returns (address payable)
{
return _servicesContractImpl;
}
function getMinimumDeposit()
external
view
override
returns (uint256)
{
return _minimumDeposit;
}
function _min(uint256 a, uint256 b) pure internal returns (uint256) {
return a <= b ? a : b;
}
}
// Copyright (C) 2021 BITFISH LIMITED
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.0;
/// @notice Governs the life cycle of a single Eth2 validator with ETH provided by multiple stakers.
interface IStakefishServicesContract {
/// @notice The life cycle of a services contract.
enum State {
NotInitialized,
PreDeposit,
PostDeposit,
Withdrawn
}
/// @notice Emitted when a `spender` is set to allow the transfer of an `owner`'s deposit stake amount.
/// `amount` is the new allownace.
/// @dev Also emitted when {transferDepositFrom} is called.
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
/// @notice Emitted when deposit stake amount is transferred.
/// @param from The address of deposit stake owner.
/// @param to The address of deposit stake beneficiary.
/// @param amount The amount of transferred deposit stake.
event Transfer(
address indexed from,
address indexed to,
uint256 amount
);
/// @notice Emitted when a `spender` is set to allow withdrawal on behalf of a `owner`.
/// `amount` is the new allowance.
/// @dev Also emitted when {WithdrawFrom} is called.
event WithdrawalApproval(
address indexed owner,
address indexed spender,
uint256 amount
);
/// @notice Emitted when `owner`'s ETH are withdrawan to `to`.
/// @param owner The address of deposit stake owner.
/// @param to The address of ETH beneficiary.
/// @param amount The amount of deposit stake to be converted to ETH.
/// @param value The amount of withdrawn ETH.
event Withdrawal(
address indexed owner,
address indexed to,
uint256 amount,
uint256 value
);
/// @notice Emitted when 32 ETH is transferred to the eth2 deposit contract.
/// @param pubkey A BLS12-381 public key.
event ValidatorDeposited(
bytes pubkey // 48 bytes
);
/// @notice Emitted when a validator exits and the operator settles the commission.
event ServiceEnd();
/// @notice Emitted when deposit to the services contract.
/// @param from The address of the deposit stake owner.
/// @param amount The accepted amount of ETH deposited into the services contract.
event Deposit(
address from,
uint256 amount
);
/// @notice Emitted when operaotr claims commission fee.
/// @param receiver The address of the operator.
/// @param amount The amount of ETH sent to the operator address.
event Claim(
address receiver,
uint256 amount
);
/// @notice Updates the exit date of the validator.
/// @dev The exit date should be in the range of uint64.
/// @param newExitDate The new exit date should come before the previously specified exit date.
function updateExitDate(uint64 newExitDate) external;
/// @notice Submits a Phase 0 DepositData to the eth2 deposit contract.
/// @dev The Keccak hash of the contract address and all submitted data should match the `_operatorDataCommitment`.
/// Emits a {ValidatorDeposited} event.
/// @param validatorPubKey A BLS12-381 public key.
/// @param depositSignature A BLS12-381 signature.
/// @param depositDataRoot The SHA-256 hash of the SSZ-encoded DepositData object.
/// @param exitDate The expected exit date of the created validator
function createValidator(
bytes calldata validatorPubKey, // 48 bytes
bytes calldata depositSignature, // 96 bytes
bytes32 depositDataRoot,
uint64 exitDate
) external;
/// @notice Deposits `msg.value` of ETH.
/// @dev If the balance of the contract exceeds 32 ETH, the excess will be sent
/// back to `msg.sender`.
/// Emits a {Deposit} event.
function deposit() external payable returns (uint256 surplus);
/// @notice Deposits `msg.value` of ETH on behalf of `depositor`.
/// @dev If the balance of the contract exceeds 32 ETH, the excess will be sent
/// back to `depositor`.
/// Emits a {Deposit} event.
function depositOnBehalfOf(address depositor) external payable returns (uint256 surplus);
/// @notice Settles operator service commission and enable withdrawal.
/// @dev It can be called by operator if the time has passed `_exitDate`.
/// It can be called by any address if the time has passed `_exitDate + MAX_SECONDS_IN_EXIT_QUEUE`.
/// Emits a {ServiceEnd} event.
function endOperatorServices() external;
/// @notice Withdraws all the ETH of `msg.sender`.
/// @dev It can only be called when the contract state is not `PostDeposit`.
/// Emits a {Withdrawal} event.
/// @param minimumETHAmount The minimum amount of ETH that must be received for the transaction not to revert.
function withdrawAll(uint256 minimumETHAmount) external returns (uint256);
/// @notice Withdraws the ETH of `msg.sender` which is corresponding to the `amount` of deposit stake.
/// @dev It can only be called when the contract state is not `PostDeposit`.
/// Emits a {Withdrawal} event.
/// @param amount The amount of deposit stake to be converted to ETH.
/// @param minimumETHAmount The minimum amount of ETH that must be received for the transaction not to revert.
function withdraw(uint256 amount, uint256 minimumETHAmount) external returns (uint256);
/// @notice Withdraws the ETH of `msg.sender` which is corresponding to the `amount` of deposit stake to a specified address.
/// @dev It can only be called when the contract state is not `PostDeposit`.
/// Emits a {Withdrawal} event.
/// @param amount The amount of deposit stake to be converted to ETH.
/// @param beneficiary The address of ETH receiver.
/// @param minimumETHAmount The minimum amount of ETH that must be received for the transaction not to revert.
function withdrawTo(
uint256 amount,
address payable beneficiary,
uint256 minimumETHAmount
) external returns (uint256);
/// @notice Sets `amount` as the allowance of `spender` over the caller's deposit stake.
/// @dev Emits an {Approval} event.
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Increases the allowance granted to `spender` by the caller.
/// @dev Emits an {Approval} event indicating the upated allowances;
function increaseAllowance(address spender, uint256 addValue) external returns (bool);
/// @notice Decreases the allowance granted to `spender` by the caller.
/// @dev Emits an {Approval} event indicating the upated allowances;
/// It reverts if current allowance is less than `subtractedValue`.
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
/// @notice Decreases the allowance granted to `spender` by the caller.
/// @dev Emits an {Approval} event indicating the upated allowances;
/// It sets allowance to zero if current allowance is less than `subtractedValue`.
function forceDecreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
/// @notice Sets `amount` as the allowance of `spender` over the caller's deposit amount that can be withdrawn.
/// @dev Emits an {WithdrawalApproval} event.
function approveWithdrawal(address spender, uint256 amount) external returns (bool);
/// @notice Increases the allowance of withdrawal granted to `spender` by the caller.
/// @dev Emits an {WithdrawalApproval} event indicating the upated allowances;
function increaseWithdrawalAllowance(address spender, uint256 addValue) external returns (bool);
/// @notice Decreases the allowance of withdrawal granted to `spender` by the caller.
/// @dev Emits an {WithdrawwalApproval} event indicating the upated allowances;
/// It reverts if current allowance is less than `subtractedValue`.
function decreaseWithdrawalAllowance(address spender, uint256 subtractedValue) external returns (bool);
/// @notice Decreases the allowance of withdrawal granted to `spender` by the caller.
/// @dev Emits an {WithdrawwalApproval} event indicating the upated allowances;
/// It reverts if current allowance is less than `subtractedValue`.
function forceDecreaseWithdrawalAllowance(address spender, uint256 subtractedValue) external returns (bool);
/// @notice Withdraws the ETH of `depositor` which is corresponding to the `amount` of deposit stake to a specified address.
/// @dev Emits a {Withdrawal} event.
/// Emits a {WithdrawalApproval} event indicating the updated allowance.
/// @param depositor The address of deposit stake holder.
/// @param beneficiary The address of ETH receiver.
/// @param amount The amount of deposit stake to be converted to ETH.
/// @param minimumETHAmount The minimum amount of ETH that must be received for the transaction not to revert.
function withdrawFrom(
address depositor,
address payable beneficiary,
uint256 amount,
uint256 minimumETHAmount
) external returns (uint256);
/// @notice Transfers `amount` deposit stake from caller to `to`.
/// @dev Emits a {Transfer} event.
function transferDeposit(address to, uint256 amount) external returns (bool);
/// @notice Transfers `amount` deposit stake from `from` to `to`.
/// @dev Emits a {Transfer} event.
/// Emits an {Approval} event indicating the updated allowance.
function transferDepositFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/// @notice Transfers operator claimable commission fee to the operator address.
/// @dev Emits a {Claim} event.
function operatorClaim() external returns (uint256);
/// @notice Returns the remaining number of deposit stake that `spender` will be allowed to withdraw
/// on behalf of `depositor` through {withdrawFrom}.
function withdrawalAllowance(address depositor, address spender) external view returns (uint256);
/// @notice Returns the operator service commission rate.
function getCommissionRate() external view returns (uint256);
/// @notice Returns operator claimable commission fee.
function getOperatorClaimable() external view returns (uint256);
/// @notice Returns the exit date of the validator.
function getExitDate() external view returns (uint256);
/// @notice Returns the state of the contract.
function getState() external view returns (State);
/// @notice Returns the address of operator.
function getOperatorAddress() external view returns (address);
/// @notice Returns the amount of deposit stake owned by `depositor`.
function getDeposit(address depositor) external view returns (uint256);
/// @notice Returns the total amount of deposit stake.
function getTotalDeposits() external view returns (uint256);
/// @notice Returns the remaining number of deposit stake that `spender` will be allowed to transfer
/// on behalf of `depositor` through {transferDepositFrom}.
function getAllowance(address owner, address spender) external view returns (uint256);
/// @notice Returns the commitment which is the hash of the contract address and all inputs to the `createValidator` function.
function getOperatorDataCommitment() external view returns (bytes32);
/// @notice Returns the amount of ETH that is withdrawable by `owner`.
function getWithdrawableAmount(address owner) external view returns (uint256);
}
// Copyright (C) 2021 BITFISH LIMITED
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.0;
/// @notice Manages the deployment of services contracts
interface IStakefishServicesContractFactory {
/// @notice Emitted when a proxy contract of the services contract is created
event ContractCreated(
bytes32 create2Salt
);
/// @notice Emitted when operator service commission rate is set or changed.
event CommissionRateChanged(
uint256 newCommissionRate
);
/// @notice Emitted when operator address is set or changed.
event OperatorChanged(
address newOperatorAddress
);
/// @notice Emitted when minimum deposit amount is changed.
event MinimumDepositChanged(
uint256 newMinimumDeposit
);
/// @notice Updates the operator service commission rate.
/// @dev Emits a {CommissionRateChanged} event.
function changeCommissionRate(uint24 newCommissionRate) external;
/// @notice Updates address of the operator.
/// @dev Emits a {OperatorChanged} event.
function changeOperatorAddress(address newAddress) external;
/// @notice Updates the minimum size of deposit allowed.
/// @dev Emits a {MinimumDeposiChanged} event.
function changeMinimumDeposit(uint256 newMinimumDeposit) external;
/// @notice Deploys a proxy contract of the services contract at a deterministic address.
/// @dev Emits a {ContractCreated} event.
function createContract(bytes32 saltValue, bytes32 operatorDataCommitmet) external payable returns (address);
/// @notice Deploys multiple proxy contracts of the services contract at deterministic addresses.
/// @dev Emits a {ContractCreated} event for each deployed proxy contract.
function createMultipleContracts(uint256 baseSaltValue, bytes32[] calldata operatorDataCommitmets) external payable;
/// @notice Funds multiple services contracts in order.
/// @dev The surplus will be returned to caller if all services contracts are filled up.
/// Using salt instead of address to prevent depositing into malicious contracts.
/// @param saltValues The salts that are used to deploy services contracts.
/// @param force If set to `false` then it will only deposit into a services contract
/// when it has more than `MINIMUM_DEPOSIT` ETH of capacity.
/// @return surplus The amount of returned ETH.
function fundMultipleContracts(bytes32[] calldata saltValues, bool force) external payable returns (uint256);
/// @notice Returns the address of the operator.
function getOperatorAddress() external view returns (address);
/// @notice Returns the operator service commission rate.
function getCommissionRate() external view returns (uint24);
/// @notice Returns the address of implementation of services contract.
function getServicesContractImpl() external view returns (address payable);
/// @notice Returns the minimum deposit amount.
function getMinimumDeposit() external view returns (uint256);
}
// Copyright (C) 2021 BITFISH LIMITED
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.4;
/// @dev https://eips.ethereum.org/EIPS/eip-1167
contract ProxyFactory {
function _getDeterministicAddress(
address target,
bytes32 salt
) internal view returns (address proxy) {
address deployer = address(this);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), shl(0x60, target))
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(clone, 0x38), shl(0x60, deployer))
mstore(add(clone, 0x4c), salt)
mstore(add(clone, 0x6c), keccak256(clone, 0x37))
proxy := keccak256(add(clone, 0x37), 0x55)
}
}
function _createProxyDeterministic(
address target,
bytes memory initData,
bytes32 salt
) internal returns (address proxy) {
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), shl(0x60, target))
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create2(0, clone, 0x37, salt)
}
require(proxy != address(0), "Proxy deploy failed");
if (initData.length > 0) {
(bool success, ) = proxy.call(initData);
require(success, "Proxy init failed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/4d0f8c1da8654a478f046ea7cf83d2166e1025af/contracts/utils/Address.sol
/**
* @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);
}
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Copyright (C) 2021 BITFISH LIMITED
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.4;
import "./interfaces/deposit_contract.sol";
import "./interfaces/IStakefishServicesContract.sol";
import "./libraries/Address.sol";
contract StakefishServicesContract is IStakefishServicesContract {
using Address for address payable;
uint256 private constant HOUR = 3600;
uint256 private constant DAY = 24 * HOUR;
uint256 private constant WEEK = 7 * DAY;
uint256 private constant YEAR = 365 * DAY;
uint256 private constant MAX_SECONDS_IN_EXIT_QUEUE = 1 * YEAR;
uint256 private constant COMMISSION_RATE_SCALE = 1000000;
// Packed into a single slot
uint24 private _commissionRate;
address private _operatorAddress;
uint64 private _exitDate;
State private _state;
bytes32 private _operatorDataCommitment;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => mapping(address => uint256)) private _allowedWithdrawals;
mapping(address => uint256) private _deposits;
uint256 private _totalDeposits;
uint256 private _operatorClaimable;
IDepositContract public constant depositContract =
IDepositContract(0x00000000219ab540356cBB839Cbe05303d7705Fa);
modifier onlyOperator() {
require(
msg.sender == _operatorAddress,
"Caller is not the operator"
);
_;
}
modifier initializer() {
require(
_state == State.NotInitialized,
"Contract is already initialized"
);
_state = State.PreDeposit;
_;
}
function initialize(
uint24 commissionRate,
address operatorAddress,
bytes32 operatorDataCommitment
)
external
initializer
{
require(uint256(commissionRate) <= COMMISSION_RATE_SCALE, "Commission rate exceeds scale");
_commissionRate = commissionRate;
_operatorAddress = operatorAddress;
_operatorDataCommitment = operatorDataCommitment;
}
receive() payable external {
if (_state == State.PreDeposit) {
revert("Plain Ether transfer not allowed");
}
}
function updateExitDate(uint64 newExitDate)
external
override
onlyOperator
{
require(
_state == State.PostDeposit,
"Validator is not active"
);
require(
newExitDate < _exitDate,
"Not earlier than the original value"
);
_exitDate = newExitDate;
}
function createValidator(
bytes calldata validatorPubKey, // 48 bytes
bytes calldata depositSignature, // 96 bytes
bytes32 depositDataRoot,
uint64 exitDate
)
external
override
onlyOperator
{
require(_state == State.PreDeposit, "Validator has been created");
_state = State.PostDeposit;
require(validatorPubKey.length == 48, "Invalid validator public key");
require(depositSignature.length == 96, "Invalid deposit signature");
require(_operatorDataCommitment == keccak256(
abi.encodePacked(
address(this),
validatorPubKey,
depositSignature,
depositDataRoot,
exitDate
)
), "Data doesn't match commitment");
_exitDate = exitDate;
depositContract.deposit{value: 32 ether}(
validatorPubKey,
abi.encodePacked(uint96(0x010000000000000000000000), address(this)),
depositSignature,
depositDataRoot
);
emit ValidatorDeposited(validatorPubKey);
}
function deposit()
external
payable
override
returns (uint256 surplus)
{
require(
_state == State.PreDeposit,
"Validator already created"
);
return _handleDeposit(msg.sender);
}
function depositOnBehalfOf(address depositor)
external
payable
override
returns (uint256 surplus)
{
require(
_state == State.PreDeposit,
"Validator already created"
);
return _handleDeposit(depositor);
}
function endOperatorServices()
external
override
{
uint256 balance = address(this).balance;
require(balance > 0, "Can't end with 0 balance");
require(_state == State.PostDeposit, "Not allowed in the current state");
require((msg.sender == _operatorAddress && block.timestamp > _exitDate) ||
(_deposits[msg.sender] > 0 && block.timestamp > _exitDate + MAX_SECONDS_IN_EXIT_QUEUE), "Not allowed at the current time");
_state = State.Withdrawn;
if (balance > 32 ether) {
uint256 profit = balance - 32 ether;
uint256 finalCommission = profit * _commissionRate / COMMISSION_RATE_SCALE;
_operatorClaimable += finalCommission;
}
emit ServiceEnd();
}
function operatorClaim()
external
override
onlyOperator
returns (uint256)
{
uint256 claimable = _operatorClaimable;
if (claimable > 0) {
_operatorClaimable = 0;
payable(_operatorAddress).sendValue(claimable);
emit Claim(_operatorAddress, claimable);
}
return claimable;
}
string private constant WITHDRAWALS_NOT_ALLOWED =
"Not allowed when validator is active";
function withdrawAll(uint256 minimumETHAmount)
external
override
returns (uint256)
{
require(_state != State.PostDeposit, WITHDRAWALS_NOT_ALLOWED);
uint256 value = _executeWithdrawal(msg.sender, payable(msg.sender), _deposits[msg.sender]);
require(value >= minimumETHAmount, "Less than minimum amount");
return value;
}
function withdraw(
uint256 amount,
uint256 minimumETHAmount
)
external
override
returns (uint256)
{
require(_state != State.PostDeposit, WITHDRAWALS_NOT_ALLOWED);
uint256 value = _executeWithdrawal(msg.sender, payable(msg.sender), amount);
require(value >= minimumETHAmount, "Less than minimum amount");
return value;
}
function withdrawTo(
uint256 amount,
address payable beneficiary,
uint256 minimumETHAmount
)
external
override
returns (uint256)
{
require(_state != State.PostDeposit, WITHDRAWALS_NOT_ALLOWED);
uint256 value = _executeWithdrawal(msg.sender, beneficiary, amount);
require(value >= minimumETHAmount, "Less than minimum amount");
return value;
}
function approve(
address spender,
uint256 amount
)
public
override
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
function increaseAllowance(
address spender,
uint256 addedValue
)
external
override
returns (bool)
{
_approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
override
returns (bool)
{
_approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue);
return true;
}
function forceDecreaseAllowance(
address spender,
uint256 subtractedValue
)
external
override
returns (bool)
{
uint256 currentAllowance = _allowances[msg.sender][spender];
_approve(msg.sender, spender, currentAllowance - _min(subtractedValue, currentAllowance));
return true;
}
function approveWithdrawal(
address spender,
uint256 amount
)
external
override
returns (bool)
{
_approveWithdrawal(msg.sender, spender, amount);
return true;
}
function increaseWithdrawalAllowance(
address spender,
uint256 addedValue
)
external
override
returns (bool)
{
_approveWithdrawal(msg.sender, spender, _allowedWithdrawals[msg.sender][spender] + addedValue);
return true;
}
function decreaseWithdrawalAllowance(
address spender,
uint256 subtractedValue
)
external
override
returns (bool)
{
_approveWithdrawal(msg.sender, spender, _allowedWithdrawals[msg.sender][spender] - subtractedValue);
return true;
}
function forceDecreaseWithdrawalAllowance(
address spender,
uint256 subtractedValue
)
external
override
returns (bool)
{
uint256 currentAllowance = _allowedWithdrawals[msg.sender][spender];
_approveWithdrawal(msg.sender, spender, currentAllowance - _min(subtractedValue, currentAllowance));
return true;
}
function withdrawFrom(
address depositor,
address payable beneficiary,
uint256 amount,
uint256 minimumETHAmount
)
external
override
returns (uint256)
{
require(_state != State.PostDeposit, WITHDRAWALS_NOT_ALLOWED);
uint256 spenderAllowance = _allowedWithdrawals[depositor][msg.sender];
uint256 newAllowance = spenderAllowance - amount;
// Please note that there is no need to require(_deposit <= spenderAllowance)
// here because modern versions of Solidity insert underflow checks
_allowedWithdrawals[depositor][msg.sender] = newAllowance;
emit WithdrawalApproval(depositor, msg.sender, newAllowance);
uint256 value = _executeWithdrawal(depositor, beneficiary, amount);
require(value >= minimumETHAmount, "Less than minimum amount");
return value;
}
function transferDeposit(
address to,
uint256 amount
)
external
override
returns (bool)
{
_transfer(msg.sender, to, amount);
return true;
}
function transferDepositFrom(
address from,
address to,
uint256 amount
)
external
override
returns (bool)
{
uint256 currentAllowance = _allowances[from][msg.sender];
_approve(from, msg.sender, currentAllowance - amount);
_transfer(from, to, amount);
return true;
}
function withdrawalAllowance(
address depositor,
address spender
)
external
view
override
returns (uint256)
{
return _allowedWithdrawals[depositor][spender];
}
function getCommissionRate()
external
view
override
returns (uint256)
{
return _commissionRate;
}
function getExitDate()
external
view
override
returns (uint256)
{
return _exitDate;
}
function getState()
external
view
override
returns(State)
{
return _state;
}
function getOperatorAddress()
external
view
override
returns (address)
{
return _operatorAddress;
}
function getDeposit(address depositor)
external
view
override
returns (uint256)
{
return _deposits[depositor];
}
function getTotalDeposits()
external
view
override
returns (uint256)
{
return _totalDeposits;
}
function getAllowance(
address owner,
address spender
)
external
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function getOperatorDataCommitment()
external
view
override
returns (bytes32)
{
return _operatorDataCommitment;
}
function getOperatorClaimable()
external
view
override
returns (uint256)
{
return _operatorClaimable;
}
function getWithdrawableAmount(address owner)
external
view
override
returns (uint256)
{
if (_state == State.PostDeposit) {
return 0;
}
return _deposits[owner] * (address(this).balance - _operatorClaimable) / _totalDeposits;
}
function _executeWithdrawal(
address depositor,
address payable beneficiary,
uint256 amount
)
internal
returns (uint256)
{
require(amount > 0, "Amount shouldn't be zero");
uint256 value = amount * (address(this).balance - _operatorClaimable) / _totalDeposits;
// Modern versions of Solidity automatically add underflow checks,
// so we don't need to `require(_deposits[_depositor] < _deposit` here:
_deposits[depositor] -= amount;
_totalDeposits -= amount;
emit Withdrawal(depositor, beneficiary, amount, value);
payable(beneficiary).sendValue(value);
return value;
}
// NOTE: This throws (on underflow) if the contract's balance was more than
// 32 ether before the call
function _handleDeposit(address depositor)
internal
returns (uint256 surplus)
{
uint256 depositSize = msg.value;
surplus = (address(this).balance > 32 ether) ?
(address(this).balance - 32 ether) : 0;
uint256 acceptedDeposit = depositSize - surplus;
_deposits[depositor] += acceptedDeposit;
_totalDeposits += acceptedDeposit;
emit Deposit(depositor, acceptedDeposit);
if (surplus > 0) {
payable(depositor).sendValue(surplus);
}
}
function _transfer(
address from,
address to,
uint256 amount
)
internal
{
require(to != address(0), "Transfer to the zero address");
_deposits[from] -= amount;
_deposits[to] += amount;
emit Transfer(from, to, amount);
}
function _approve(
address owner,
address spender,
uint256 amount
)
internal
{
require(spender != address(0), "Approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _approveWithdrawal(
address owner,
address spender,
uint256 amount
)
internal
{
require(spender != address(0), "Approve to the zero address");
_allowedWithdrawals[owner][spender] = amount;
emit WithdrawalApproval(owner, spender, amount);
}
function _min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
// ┏━━━┓━┏┓━┏┓━━┏━━━┓━━┏━━━┓━━━━┏━━━┓━━━━━━━━━━━━━━━━━━━┏┓━━━━━┏━━━┓━━━━━━━━━┏┓━━━━━━━━━━━━━━┏┓━
// ┃┏━━┛┏┛┗┓┃┃━━┃┏━┓┃━━┃┏━┓┃━━━━┗┓┏┓┃━━━━━━━━━━━━━━━━━━┏┛┗┓━━━━┃┏━┓┃━━━━━━━━┏┛┗┓━━━━━━━━━━━━┏┛┗┓
// ┃┗━━┓┗┓┏┛┃┗━┓┗┛┏┛┃━━┃┃━┃┃━━━━━┃┃┃┃┏━━┓┏━━┓┏━━┓┏━━┓┏┓┗┓┏┛━━━━┃┃━┗┛┏━━┓┏━┓━┗┓┏┛┏━┓┏━━┓━┏━━┓┗┓┏┛
// ┃┏━━┛━┃┃━┃┏┓┃┏━┛┏┛━━┃┃━┃┃━━━━━┃┃┃┃┃┏┓┃┃┏┓┃┃┏┓┃┃━━┫┣┫━┃┃━━━━━┃┃━┏┓┃┏┓┃┃┏┓┓━┃┃━┃┏┛┗━┓┃━┃┏━┛━┃┃━
// ┃┗━━┓━┃┗┓┃┃┃┃┃┃┗━┓┏┓┃┗━┛┃━━━━┏┛┗┛┃┃┃━┫┃┗┛┃┃┗┛┃┣━━┃┃┃━┃┗┓━━━━┃┗━┛┃┃┗┛┃┃┃┃┃━┃┗┓┃┃━┃┗┛┗┓┃┗━┓━┃┗┓
// ┗━━━┛━┗━┛┗┛┗┛┗━━━┛┗┛┗━━━┛━━━━┗━━━┛┗━━┛┃┏━┛┗━━┛┗━━┛┗┛━┗━┛━━━━┗━━━┛┗━━┛┗┛┗┛━┗━┛┗┛━┗━━━┛┗━━┛━┗━┛
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┃┃━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┗┛━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// SPDX-License-Identifier: CC0-1.0
pragma solidity 0.8.4;
// This interface is designed to be compatible with the Vyper version.
/// @notice This is the Ethereum 2.0 deposit contract interface.
/// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs
interface IDepositContract {
/// @notice A processed deposit event.
event DepositEvent(
bytes pubkey,
bytes withdrawal_credentials,
bytes amount,
bytes signature,
bytes index
);
/// @notice Submit a Phase 0 DepositData object.
/// @param pubkey A BLS12-381 public key.
/// @param withdrawal_credentials Commitment to a public key for withdrawals.
/// @param signature A BLS12-381 signature.
/// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object.
/// Used as a protection against malformed input.
function deposit(
bytes calldata pubkey,
bytes calldata withdrawal_credentials,
bytes calldata signature,
bytes32 deposit_data_root
) external payable;
/// @notice Query the current deposit root hash.
/// @return The deposit root hash.
function get_deposit_root() external view returns (bytes32);
/// @notice Query the current deposit count.
/// @return The deposit count encoded as a little endian 64-bit number.
function get_deposit_count() external view returns (bytes memory);
}
// Based on official specification in https://eips.ethereum.org/EIPS/eip-165
interface ERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceId` and
/// `interfaceId` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceId) external pure returns (bool);
}
// This is a rewrite of the Vyper Eth2.0 deposit contract in Solidity.
// It tries to stay as close as possible to the original source code.
/// @notice This is the Ethereum 2.0 deposit contract interface.
/// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs
contract DepositContract is IDepositContract, ERC165 {
uint constant DEPOSIT_CONTRACT_TREE_DEPTH = 32;
// NOTE: this also ensures `deposit_count` will fit into 64-bits
uint constant MAX_DEPOSIT_COUNT = 2**DEPOSIT_CONTRACT_TREE_DEPTH - 1;
bytes32[DEPOSIT_CONTRACT_TREE_DEPTH] branch;
uint256 deposit_count;
bytes32[DEPOSIT_CONTRACT_TREE_DEPTH] zero_hashes;
constructor() {
// Compute hashes in empty sparse Merkle tree
for (uint height = 0; height < DEPOSIT_CONTRACT_TREE_DEPTH - 1; height++)
zero_hashes[height + 1] = sha256(abi.encodePacked(zero_hashes[height], zero_hashes[height]));
}
function get_deposit_root() override external view returns (bytes32) {
bytes32 node;
uint size = deposit_count;
for (uint height = 0; height < DEPOSIT_CONTRACT_TREE_DEPTH; height++) {
if ((size & 1) == 1)
node = sha256(abi.encodePacked(branch[height], node));
else
node = sha256(abi.encodePacked(node, zero_hashes[height]));
size /= 2;
}
return sha256(abi.encodePacked(
node,
to_little_endian_64(uint64(deposit_count)),
bytes24(0)
));
}
function get_deposit_count() override external view returns (bytes memory) {
return to_little_endian_64(uint64(deposit_count));
}
function deposit(
bytes calldata pubkey,
bytes calldata withdrawal_credentials,
bytes calldata signature,
bytes32 deposit_data_root
) override external payable {
// Extended ABI length checks since dynamic types are used.
require(pubkey.length == 48, "DepositContract: invalid pubkey length");
require(withdrawal_credentials.length == 32, "DepositContract: invalid withdrawal_credentials length");
require(signature.length == 96, "DepositContract: invalid signature length");
// Check deposit amount
require(msg.value >= 1 ether, "DepositContract: deposit value too low");
require(msg.value % 1 gwei == 0, "DepositContract: deposit value not multiple of gwei");
uint deposit_amount = msg.value / 1 gwei;
require(deposit_amount <= type(uint64).max, "DepositContract: deposit value too high");
// Emit `DepositEvent` log
bytes memory amount = to_little_endian_64(uint64(deposit_amount));
emit DepositEvent(
pubkey,
withdrawal_credentials,
amount,
signature,
to_little_endian_64(uint64(deposit_count))
);
// Compute deposit data root (`DepositData` hash tree root)
bytes32 pubkey_root = sha256(abi.encodePacked(pubkey, bytes16(0)));
bytes32 signature_root = sha256(abi.encodePacked(
sha256(abi.encodePacked(signature[:64])),
sha256(abi.encodePacked(signature[64:], bytes32(0)))
));
bytes32 node = sha256(abi.encodePacked(
sha256(abi.encodePacked(pubkey_root, withdrawal_credentials)),
sha256(abi.encodePacked(amount, bytes24(0), signature_root))
));
// Verify computed and expected deposit data roots match
require(node == deposit_data_root, "DepositContract: reconstructed DepositData does not match supplied deposit_data_root");
// Avoid overflowing the Merkle tree (and prevent edge case in computing `branch`)
require(deposit_count < MAX_DEPOSIT_COUNT, "DepositContract: merkle tree full");
// Add deposit data root to Merkle tree (update a single `branch` node)
deposit_count += 1;
uint size = deposit_count;
for (uint height = 0; height < DEPOSIT_CONTRACT_TREE_DEPTH; height++) {
if ((size & 1) == 1) {
branch[height] = node;
return;
}
node = sha256(abi.encodePacked(branch[height], node));
size /= 2;
}
// As the loop should always end prematurely with the `return` statement,
// this code should be unreachable. We assert `false` just to be safe.
assert(false);
}
function supportsInterface(bytes4 interfaceId) override external pure returns (bool) {
return interfaceId == type(ERC165).interfaceId || interfaceId == type(IDepositContract).interfaceId;
}
function to_little_endian_64(uint64 value) internal pure returns (bytes memory ret) {
ret = new bytes(8);
bytes8 bytesValue = bytes8(value);
// Byteswapping during copying to bytes.
ret[0] = bytesValue[7];
ret[1] = bytesValue[6];
ret[2] = bytesValue[5];
ret[3] = bytesValue[4];
ret[4] = bytesValue[3];
ret[5] = bytesValue[2];
ret[6] = bytesValue[1];
ret[7] = bytesValue[0];
}
}
| Packed into a single slot | contract StakefishServicesContract is IStakefishServicesContract {
using Address for address payable;
uint256 private constant HOUR = 3600;
uint256 private constant DAY = 24 * HOUR;
uint256 private constant WEEK = 7 * DAY;
uint256 private constant YEAR = 365 * DAY;
uint256 private constant MAX_SECONDS_IN_EXIT_QUEUE = 1 * YEAR;
uint256 private constant COMMISSION_RATE_SCALE = 1000000;
uint24 private _commissionRate;
address private _operatorAddress;
uint64 private _exitDate;
State private _state;
bytes32 private _operatorDataCommitment;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => mapping(address => uint256)) private _allowedWithdrawals;
mapping(address => uint256) private _deposits;
uint256 private _totalDeposits;
uint256 private _operatorClaimable;
IDepositContract public constant depositContract =
IDepositContract(0x00000000219ab540356cBB839Cbe05303d7705Fa);
modifier onlyOperator() {
require(
msg.sender == _operatorAddress,
"Caller is not the operator"
);
_;
}
modifier initializer() {
require(
_state == State.NotInitialized,
"Contract is already initialized"
);
_state = State.PreDeposit;
_;
}
function initialize(
uint24 commissionRate,
address operatorAddress,
bytes32 operatorDataCommitment
)
external
initializer
{
require(uint256(commissionRate) <= COMMISSION_RATE_SCALE, "Commission rate exceeds scale");
_commissionRate = commissionRate;
_operatorAddress = operatorAddress;
_operatorDataCommitment = operatorDataCommitment;
}
receive() payable external {
if (_state == State.PreDeposit) {
revert("Plain Ether transfer not allowed");
}
}
receive() payable external {
if (_state == State.PreDeposit) {
revert("Plain Ether transfer not allowed");
}
}
function updateExitDate(uint64 newExitDate)
external
override
onlyOperator
{
require(
_state == State.PostDeposit,
"Validator is not active"
);
require(
newExitDate < _exitDate,
"Not earlier than the original value"
);
_exitDate = newExitDate;
}
function createValidator(
bytes32 depositDataRoot,
uint64 exitDate
)
external
override
onlyOperator
{
require(_state == State.PreDeposit, "Validator has been created");
_state = State.PostDeposit;
require(validatorPubKey.length == 48, "Invalid validator public key");
require(depositSignature.length == 96, "Invalid deposit signature");
require(_operatorDataCommitment == keccak256(
abi.encodePacked(
address(this),
validatorPubKey,
depositSignature,
depositDataRoot,
exitDate
)
), "Data doesn't match commitment");
_exitDate = exitDate;
validatorPubKey,
abi.encodePacked(uint96(0x010000000000000000000000), address(this)),
depositSignature,
depositDataRoot
);
emit ValidatorDeposited(validatorPubKey);
}
depositContract.deposit{value: 32 ether}(
function deposit()
external
payable
override
returns (uint256 surplus)
{
require(
_state == State.PreDeposit,
"Validator already created"
);
return _handleDeposit(msg.sender);
}
function depositOnBehalfOf(address depositor)
external
payable
override
returns (uint256 surplus)
{
require(
_state == State.PreDeposit,
"Validator already created"
);
return _handleDeposit(depositor);
}
function endOperatorServices()
external
override
{
uint256 balance = address(this).balance;
require(balance > 0, "Can't end with 0 balance");
require(_state == State.PostDeposit, "Not allowed in the current state");
require((msg.sender == _operatorAddress && block.timestamp > _exitDate) ||
(_deposits[msg.sender] > 0 && block.timestamp > _exitDate + MAX_SECONDS_IN_EXIT_QUEUE), "Not allowed at the current time");
_state = State.Withdrawn;
if (balance > 32 ether) {
uint256 profit = balance - 32 ether;
uint256 finalCommission = profit * _commissionRate / COMMISSION_RATE_SCALE;
_operatorClaimable += finalCommission;
}
emit ServiceEnd();
}
function endOperatorServices()
external
override
{
uint256 balance = address(this).balance;
require(balance > 0, "Can't end with 0 balance");
require(_state == State.PostDeposit, "Not allowed in the current state");
require((msg.sender == _operatorAddress && block.timestamp > _exitDate) ||
(_deposits[msg.sender] > 0 && block.timestamp > _exitDate + MAX_SECONDS_IN_EXIT_QUEUE), "Not allowed at the current time");
_state = State.Withdrawn;
if (balance > 32 ether) {
uint256 profit = balance - 32 ether;
uint256 finalCommission = profit * _commissionRate / COMMISSION_RATE_SCALE;
_operatorClaimable += finalCommission;
}
emit ServiceEnd();
}
function operatorClaim()
external
override
onlyOperator
returns (uint256)
{
uint256 claimable = _operatorClaimable;
if (claimable > 0) {
_operatorClaimable = 0;
payable(_operatorAddress).sendValue(claimable);
emit Claim(_operatorAddress, claimable);
}
return claimable;
}
string private constant WITHDRAWALS_NOT_ALLOWED =
"Not allowed when validator is active";
function operatorClaim()
external
override
onlyOperator
returns (uint256)
{
uint256 claimable = _operatorClaimable;
if (claimable > 0) {
_operatorClaimable = 0;
payable(_operatorAddress).sendValue(claimable);
emit Claim(_operatorAddress, claimable);
}
return claimable;
}
string private constant WITHDRAWALS_NOT_ALLOWED =
"Not allowed when validator is active";
function withdrawAll(uint256 minimumETHAmount)
external
override
returns (uint256)
{
require(_state != State.PostDeposit, WITHDRAWALS_NOT_ALLOWED);
uint256 value = _executeWithdrawal(msg.sender, payable(msg.sender), _deposits[msg.sender]);
require(value >= minimumETHAmount, "Less than minimum amount");
return value;
}
function withdraw(
uint256 amount,
uint256 minimumETHAmount
)
external
override
returns (uint256)
{
require(_state != State.PostDeposit, WITHDRAWALS_NOT_ALLOWED);
uint256 value = _executeWithdrawal(msg.sender, payable(msg.sender), amount);
require(value >= minimumETHAmount, "Less than minimum amount");
return value;
}
function withdrawTo(
uint256 amount,
address payable beneficiary,
uint256 minimumETHAmount
)
external
override
returns (uint256)
{
require(_state != State.PostDeposit, WITHDRAWALS_NOT_ALLOWED);
uint256 value = _executeWithdrawal(msg.sender, beneficiary, amount);
require(value >= minimumETHAmount, "Less than minimum amount");
return value;
}
function approve(
address spender,
uint256 amount
)
public
override
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
function increaseAllowance(
address spender,
uint256 addedValue
)
external
override
returns (bool)
{
_approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
override
returns (bool)
{
_approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue);
return true;
}
function forceDecreaseAllowance(
address spender,
uint256 subtractedValue
)
external
override
returns (bool)
{
uint256 currentAllowance = _allowances[msg.sender][spender];
_approve(msg.sender, spender, currentAllowance - _min(subtractedValue, currentAllowance));
return true;
}
function approveWithdrawal(
address spender,
uint256 amount
)
external
override
returns (bool)
{
_approveWithdrawal(msg.sender, spender, amount);
return true;
}
function increaseWithdrawalAllowance(
address spender,
uint256 addedValue
)
external
override
returns (bool)
{
_approveWithdrawal(msg.sender, spender, _allowedWithdrawals[msg.sender][spender] + addedValue);
return true;
}
function decreaseWithdrawalAllowance(
address spender,
uint256 subtractedValue
)
external
override
returns (bool)
{
_approveWithdrawal(msg.sender, spender, _allowedWithdrawals[msg.sender][spender] - subtractedValue);
return true;
}
function forceDecreaseWithdrawalAllowance(
address spender,
uint256 subtractedValue
)
external
override
returns (bool)
{
uint256 currentAllowance = _allowedWithdrawals[msg.sender][spender];
_approveWithdrawal(msg.sender, spender, currentAllowance - _min(subtractedValue, currentAllowance));
return true;
}
function withdrawFrom(
address depositor,
address payable beneficiary,
uint256 amount,
uint256 minimumETHAmount
)
external
override
returns (uint256)
{
require(_state != State.PostDeposit, WITHDRAWALS_NOT_ALLOWED);
uint256 spenderAllowance = _allowedWithdrawals[depositor][msg.sender];
uint256 newAllowance = spenderAllowance - amount;
_allowedWithdrawals[depositor][msg.sender] = newAllowance;
emit WithdrawalApproval(depositor, msg.sender, newAllowance);
uint256 value = _executeWithdrawal(depositor, beneficiary, amount);
require(value >= minimumETHAmount, "Less than minimum amount");
return value;
}
function transferDeposit(
address to,
uint256 amount
)
external
override
returns (bool)
{
_transfer(msg.sender, to, amount);
return true;
}
function transferDepositFrom(
address from,
address to,
uint256 amount
)
external
override
returns (bool)
{
uint256 currentAllowance = _allowances[from][msg.sender];
_approve(from, msg.sender, currentAllowance - amount);
_transfer(from, to, amount);
return true;
}
function withdrawalAllowance(
address depositor,
address spender
)
external
view
override
returns (uint256)
{
return _allowedWithdrawals[depositor][spender];
}
function getCommissionRate()
external
view
override
returns (uint256)
{
return _commissionRate;
}
function getExitDate()
external
view
override
returns (uint256)
{
return _exitDate;
}
function getState()
external
view
override
returns(State)
{
return _state;
}
function getOperatorAddress()
external
view
override
returns (address)
{
return _operatorAddress;
}
function getDeposit(address depositor)
external
view
override
returns (uint256)
{
return _deposits[depositor];
}
function getTotalDeposits()
external
view
override
returns (uint256)
{
return _totalDeposits;
}
function getAllowance(
address owner,
address spender
)
external
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function getOperatorDataCommitment()
external
view
override
returns (bytes32)
{
return _operatorDataCommitment;
}
function getOperatorClaimable()
external
view
override
returns (uint256)
{
return _operatorClaimable;
}
function getWithdrawableAmount(address owner)
external
view
override
returns (uint256)
{
if (_state == State.PostDeposit) {
return 0;
}
return _deposits[owner] * (address(this).balance - _operatorClaimable) / _totalDeposits;
}
function getWithdrawableAmount(address owner)
external
view
override
returns (uint256)
{
if (_state == State.PostDeposit) {
return 0;
}
return _deposits[owner] * (address(this).balance - _operatorClaimable) / _totalDeposits;
}
function _executeWithdrawal(
address depositor,
address payable beneficiary,
uint256 amount
)
internal
returns (uint256)
{
require(amount > 0, "Amount shouldn't be zero");
uint256 value = amount * (address(this).balance - _operatorClaimable) / _totalDeposits;
_deposits[depositor] -= amount;
_totalDeposits -= amount;
emit Withdrawal(depositor, beneficiary, amount, value);
payable(beneficiary).sendValue(value);
return value;
}
function _handleDeposit(address depositor)
internal
returns (uint256 surplus)
{
uint256 depositSize = msg.value;
surplus = (address(this).balance > 32 ether) ?
(address(this).balance - 32 ether) : 0;
uint256 acceptedDeposit = depositSize - surplus;
_deposits[depositor] += acceptedDeposit;
_totalDeposits += acceptedDeposit;
emit Deposit(depositor, acceptedDeposit);
if (surplus > 0) {
payable(depositor).sendValue(surplus);
}
}
function _handleDeposit(address depositor)
internal
returns (uint256 surplus)
{
uint256 depositSize = msg.value;
surplus = (address(this).balance > 32 ether) ?
(address(this).balance - 32 ether) : 0;
uint256 acceptedDeposit = depositSize - surplus;
_deposits[depositor] += acceptedDeposit;
_totalDeposits += acceptedDeposit;
emit Deposit(depositor, acceptedDeposit);
if (surplus > 0) {
payable(depositor).sendValue(surplus);
}
}
function _transfer(
address from,
address to,
uint256 amount
)
internal
{
require(to != address(0), "Transfer to the zero address");
_deposits[from] -= amount;
_deposits[to] += amount;
emit Transfer(from, to, amount);
}
function _approve(
address owner,
address spender,
uint256 amount
)
internal
{
require(spender != address(0), "Approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _approveWithdrawal(
address owner,
address spender,
uint256 amount
)
internal
{
require(spender != address(0), "Approve to the zero address");
_allowedWithdrawals[owner][spender] = amount;
emit WithdrawalApproval(owner, spender, amount);
}
function _min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
| 1,754,721 | [
1,
4420,
329,
1368,
279,
2202,
4694,
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,
934,
911,
22905,
5676,
8924,
353,
467,
510,
911,
22905,
5676,
8924,
288,
203,
565,
1450,
5267,
364,
1758,
8843,
429,
31,
203,
203,
565,
2254,
5034,
3238,
5381,
17001,
273,
12396,
31,
203,
565,
2254,
5034,
3238,
5381,
11579,
273,
4248,
380,
17001,
31,
203,
565,
2254,
5034,
3238,
5381,
26664,
273,
2371,
380,
11579,
31,
203,
565,
2254,
5034,
3238,
5381,
16145,
273,
21382,
380,
11579,
31,
203,
565,
2254,
5034,
3238,
5381,
4552,
67,
11609,
67,
706,
67,
28682,
67,
19533,
273,
404,
380,
16145,
31,
203,
565,
2254,
5034,
3238,
5381,
5423,
15566,
67,
24062,
67,
19378,
273,
15088,
31,
203,
203,
565,
2254,
3247,
3238,
389,
832,
3951,
4727,
31,
203,
565,
1758,
3238,
389,
9497,
1887,
31,
203,
565,
2254,
1105,
3238,
389,
8593,
1626,
31,
203,
565,
3287,
3238,
389,
2019,
31,
203,
203,
565,
1731,
1578,
3238,
389,
9497,
751,
5580,
475,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
8151,
1190,
9446,
1031,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
323,
917,
1282,
31,
203,
565,
2254,
5034,
3238,
389,
4963,
758,
917,
1282,
31,
203,
565,
2254,
5034,
3238,
389,
9497,
9762,
429,
31,
203,
203,
565,
467,
758,
1724,
8924,
1071,
5381,
443,
1724,
8924,
273,
203,
3639,
467,
758,
1724,
8924,
12,
20,
92,
12648,
22,
3657,
378,
6564,
2
] |
./partial_match/42/0xc95dDf6B704f30258Dd252B8dB551889a34075E2/sources/SortedMarket.sol | delete an order from the sorted list no prev entry exists. this was the first; so now next entry is first prev entry exists. fix it up. this was the last; so now prev entry is the last no next entry exists. this was the last; so now prev entry is last next entry exists. fix it up. this was the first; so now next entry is the first | function deleteOrder(uint256 _id) internal {
OpenOrder storage _openOrder = openOrders[_id];
uint256 _prevEntryIdx = _openOrder.prevSortedOrder;
uint256 _nextEntryIdx = _openOrder.nextSortedOrder;
uint256 _contractMemoId = _openOrder.contractMemo;
if (_prevEntryIdx == 0) {
if (_openOrder.isBid)
highestBidEntryIdx[_contractMemoId] = _nextEntryIdx;
else
lowestAskEntryIdx[_contractMemoId] = _nextEntryIdx;
OpenOrder storage _prevOrder = openOrders[_prevEntryIdx];
_prevOrder.nextSortedOrder = _nextEntryIdx;
if (_nextEntryIdx == 0) {
if (_openOrder.isBid)
lowestBidEntryIdx[_contractMemoId] = _prevEntryIdx;
else
highestAskEntryIdx[_contractMemoId] = _prevEntryIdx;
}
}
if (_nextEntryIdx == 0) {
if (_openOrder.isBid)
lowestBidEntryIdx[_contractMemoId] = _prevEntryIdx;
else
highestAskEntryIdx[_contractMemoId] = _prevEntryIdx;
OpenOrder storage _nextOrder = openOrders[_nextEntryIdx];
_nextOrder.prevSortedOrder = _prevEntryIdx;
if (_prevEntryIdx == 0) {
if (_openOrder.isBid)
highestBidEntryIdx[_contractMemoId] = _nextEntryIdx;
else
lowestAskEntryIdx[_contractMemoId] = _nextEntryIdx;
}
}
}
| 3,492,605 | [
1,
3733,
392,
1353,
628,
326,
3115,
666,
1158,
2807,
1241,
1704,
18,
333,
1703,
326,
1122,
31,
1427,
2037,
1024,
1241,
353,
1122,
2807,
1241,
1704,
18,
2917,
518,
731,
18,
333,
1703,
326,
1142,
31,
1427,
2037,
2807,
1241,
353,
326,
1142,
1158,
1024,
1241,
1704,
18,
333,
1703,
326,
1142,
31,
1427,
2037,
2807,
1241,
353,
1142,
1024,
1241,
1704,
18,
2917,
518,
731,
18,
333,
1703,
326,
1122,
31,
1427,
2037,
1024,
1241,
353,
326,
1122,
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,
225,
445,
1430,
2448,
12,
11890,
5034,
389,
350,
13,
2713,
288,
203,
565,
3502,
2448,
2502,
389,
3190,
2448,
273,
1696,
16528,
63,
67,
350,
15533,
203,
565,
2254,
5034,
389,
10001,
1622,
4223,
273,
389,
3190,
2448,
18,
10001,
11739,
2448,
31,
203,
565,
2254,
5034,
389,
4285,
1622,
4223,
273,
389,
3190,
2448,
18,
4285,
11739,
2448,
31,
203,
565,
2254,
5034,
389,
16351,
21230,
548,
273,
389,
3190,
2448,
18,
16351,
21230,
31,
203,
565,
309,
261,
67,
10001,
1622,
4223,
422,
374,
13,
288,
203,
1377,
309,
261,
67,
3190,
2448,
18,
291,
17763,
13,
203,
202,
8766,
395,
17763,
1622,
4223,
63,
67,
16351,
21230,
548,
65,
273,
389,
4285,
1622,
4223,
31,
203,
1377,
469,
203,
202,
821,
395,
23663,
1622,
4223,
63,
67,
16351,
21230,
548,
65,
273,
389,
4285,
1622,
4223,
31,
203,
1377,
3502,
2448,
2502,
389,
10001,
2448,
273,
1696,
16528,
63,
67,
10001,
1622,
4223,
15533,
203,
1377,
389,
10001,
2448,
18,
4285,
11739,
2448,
273,
389,
4285,
1622,
4223,
31,
203,
1377,
309,
261,
67,
4285,
1622,
4223,
422,
374,
13,
288,
203,
202,
430,
261,
67,
3190,
2448,
18,
291,
17763,
13,
203,
202,
225,
11981,
17763,
1622,
4223,
63,
67,
16351,
21230,
548,
65,
273,
389,
10001,
1622,
4223,
31,
203,
202,
12107,
203,
202,
225,
9742,
23663,
1622,
4223,
63,
67,
16351,
21230,
548,
65,
273,
389,
10001,
1622,
4223,
31,
203,
1377,
289,
203,
565,
289,
203,
565,
309,
261,
67,
4285,
1622,
4223,
422,
374,
13,
2
] |
pragma solidity ^0.5.1;
import "./Client.sol";
import "../../platform/dispatch/DispatchInterface.sol";
import "../../platform/bondage/BondageInterface.sol";
import "../../platform/registry/RegistryInterface.sol";
import "./OnChainProvider.sol";
import "../ERC20.sol";
import "hardhat/console.sol";
contract OffChainClient is Client1, Client2{
event MadeQuery(address oracle, string query, uint256 id);
event Result1(uint256 id, string response1);
event Result32(uint256 id, bytes32 response1);
event Result2(uint256 id, string response1, string response2);
event Result3(uint256 id, int[] response3);
mapping(uint=>string) public queryResults;
mapping(uint=>bytes32[]) public queryBytes32Results;
mapping(uint=>int[]) public queryIntResults;
mapping(uint=>uint) public queryBytes32IDs;
mapping(uint=>uint) public queryIntIDs;
mapping(uint=>uint) public queryIDs;
uint public totalQueries;
uint public totalIntQueries;
uint public totalBytes32Queries;
ERC20 token;
DispatchInterface dispatch;
BondageInterface bondage;
RegistryInterface registry;
constructor(address tokenAddress, address dispatchAddress, address bondageAddress, address registryAddress) public {
token = ERC20(tokenAddress);
dispatch = DispatchInterface(dispatchAddress);
bondage = BondageInterface(bondageAddress);
registry = RegistryInterface(registryAddress);
//Oracle =oracle;
}
modifier onlyOracle(){
require(msg.sender==address(dispatch),"caller must the dispatch address ");
_;
}
/*
Implements overloaded callback functions for Client1
*/
function callback(uint256 id, string calldata response1) external onlyOracle() {
//string memory _response1 = response1;
queryResults[id]=response1;
queryIDs[totalQueries]=id;
totalQueries++;
emit Result1(id, response1);
// do something with result
}
function Callback(uint256 id, string calldata response1) external onlyOracle() {
string memory _response1 = response1;
emit Result1(id, _response1);
// do something with result
}
function callback(uint256 id, bytes32[] calldata response) external onlyOracle() {
emit Result32(id, response[0]);
queryBytes32Results[id]=response;
queryBytes32IDs[totalBytes32Queries]=id;
totalBytes32Queries++;
// do something with result
}
function callback(uint256 id, int[] calldata response) external onlyOracle() {
emit Result3(id, response);
queryIntResults[id]=response;
queryIntIDs[totalIntQueries]=id;
totalIntQueries++;
// do something with result
}
// Client2 callback
function callback(uint256 id, string calldata response1, string calldata response2) external onlyOracle() {
string memory concat=string(abi.encodePacked(response1,response2));
queryResults[id]=concat;
queryIDs[totalQueries]=id;
totalQueries++;
emit Result2(id, response1, response2);
}
function testQuery(address oracleAddr, string calldata query, bytes32 specifier, bytes32[] calldata params) external returns (uint256) {
uint256 id = dispatch.query(oracleAddr, query, specifier, params);
emit MadeQuery(oracleAddr, query, id);
return id;
}
function getQueryResultById(uint id) public view returns(string memory ){
return queryResults[id];
}
function getQueryIntResultById(uint id) public view returns(int[] memory ){
return queryIntResults[id];
}
function getQueryResultByOrder(uint pos) public view returns(string memory){
uint id=queryIDs[pos];
return queryResults[id];
}
function getQueryIntResultByOrder(uint pos) public view returns(int[] memory ){
uint id=queryIntIDs[pos];
return queryIntResults[id];
}
function getQueryBytes32ResultById(uint id) public view returns(bytes32[] memory){
return queryBytes32Results[id];
}
function getQueryBytes32ResultByOrder(uint pos) public view returns(bytes32[] memory){
uint id=queryBytes32IDs[pos];
return queryBytes32Results[id];
}
function getQueryIntResultByData(uint blockNumber,uint timestamp,string memory query,address subscriber,address provider) public view returns(int[] memory){
uint id=uint256(keccak256(abi.encodePacked(block.number, now, query, subscriber, provider)));
return queryIntResults[id];
}
function getQueryResultByData(uint blockNumber,uint timestamp,string memory query,address subscriber,address provider) public view returns(string memory){
uint id=uint256(keccak256(abi.encodePacked(block.number, now, query, subscriber, provider)));
return queryResults[id];
}
function getQueryBytesResultByData(uint blockNumber,uint timestamp,string memory query,address subscriber,address provider) public view returns(bytes32[] memory){
uint id=uint256(keccak256(abi.encodePacked(block.number, now,query, subscriber, provider)));
return queryBytes32Results[id];
}
function stringToBytes32(string memory source) internal pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
// attempts to cancel an existing query
function cancelQuery(uint256 id) external {
dispatch.cancelQuery(id);
}
}
| do something with result | function Callback(uint256 id, string calldata response1) external onlyOracle() {
string memory _response1 = response1;
emit Result1(id, _response1);
}
| 12,946,605 | [
1,
2896,
5943,
598,
563,
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,
8444,
12,
11890,
5034,
612,
16,
533,
745,
892,
766,
21,
13,
3903,
225,
1338,
23601,
1435,
288,
203,
3639,
533,
3778,
389,
2740,
21,
273,
766,
21,
31,
203,
3639,
3626,
3438,
21,
12,
350,
16,
389,
2740,
21,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x024d23Dc6c813a7C26ad3Cbb102cB0c1a98DdDa9/sources/contracts/ZhouVillage.sol | * @dev Interface of ERC721 token receiver./ | interface ERC721A__IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
pragma solidity ^0.8.13;
}
| 3,850,081 | [
1,
1358,
434,
4232,
39,
27,
5340,
1147,
5971,
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
] | [
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,
5831,
4232,
39,
27,
5340,
37,
972,
45,
654,
39,
27,
5340,
12952,
288,
203,
565,
445,
603,
654,
39,
27,
5340,
8872,
12,
203,
3639,
1758,
3726,
16,
203,
3639,
1758,
628,
16,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
3903,
1135,
261,
3890,
24,
1769,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
3437,
31,
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
] |
/******************************************************************************\
file: Withdrawable.sol
ver: 0.4.3
updated:16-Aug-2018
author: Darryl Morris (o0ragman0o)
email: o0ragman0o AT gmail.com
A contract interface presenting an API for withdrawal functionality of ether
balances and inter-contract pull and push payments. Caller permissions should
be left permissive to facilitate 'clearing house' operations.
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See MIT Licence for further details.
<https://opensource.org/licenses/MIT>.
Change Log
----------
* Using Solidity 0.4.24 syntax
* dropped use of `interface` and reverting back to abstract contracts. see:
https://github.com/ethereum/solidity/issues/4832
* Changed from `Itfc` to `Abstract` suffix
\******************************************************************************/
pragma solidity ^0.4.24;
// The minimum interface supporting pull payments with deposits and withdrawl
// events
contract WithdrawableMinAbstract
{
//
// Events
//
/// @dev Logged upon receiving a deposit
/// @param _from The address from which value has been recieved
/// @param _value The value of ether received
event Deposit(address indexed _from, uint _value);
/// @dev Logged upon a withdrawal
/// @param _from the address accounted to have owned the ether
/// @param _to Address to which value was sent
/// @param _value The value in ether which was withdrawn
event Withdrawal(address indexed _from, address indexed _to, uint _value);
/// @notice withdraw total balance from account `msg.sender`
/// @return success
function withdrawAll() public returns (bool);
}
// The extended interface of optional API state variables, functions, and events
contract WithdrawableAbstract
{
//
// Events
//
/// @dev Logged upon receiving a deposit
/// @param _from The address from which value has been recieved
/// @param _value The value of ether received
event Deposit(address indexed _from, uint _value);
/// @dev Logged upon a withdrawal
/// @param _from the address accounted to have owned the ether
/// @param _to Address to which value was sent
/// @param _value The value in ether which was withdrawn
event Withdrawal(address indexed _from, address indexed _to, uint _value);
//
// Function Abstracts
//
/// @param _addr An ethereum address
/// @return The balance of ether held in the contract for `_addr`
function etherBalanceOf(address _addr) public view returns (uint);
/// @notice withdraw total balance from account `msg.sender`
/// @return Boolean success value
function withdrawAll() public returns (bool);
/// @notice Withdraw `_value` from account `msg.sender`
/// @param _value the value to withdraw
/// @return Boolean success value
function withdraw(uint _value) public returns (bool);
/// @notice Withdraw `_value` from account `msg.sender` and send `_value` to
/// address `_to`
/// @param _to a recipient address
/// @param _value the value to withdraw
/// @return Boolean success value
function withdrawTo(address _to, uint _value) public returns (bool);
/// @notice Withdraw total balance for an array of accounts
/// @param _addrs An array of address to withraw for
/// @return Boolean success value
function withdrawAllFor(address[] _addrs) public returns (bool);
/// @notice Withdraw respective values for an array of addresses
/// @param _addrs An array of address to withraw for
/// @param _values An array of values to withdraw
/// @dev Values must be valid or the call will throw
/// @return Boolean success value
function withdrawFor(address[] _addrs, uint[] _values) public returns (bool);
/// @notice Have this contract withdraw from contract at `_from`
/// @param _from a contract address where this contract's value is held
/// @return Boolean success value
function withdrawAllFrom(address _from) public returns (bool);
/// @notice Have this contract withdraw `_value` from contract at `_from`
/// @param _from a contract address where this contract's value is held
/// @param _value the value to withdraw
/// @return Boolean success value
function withdrawFrom(address _from, uint _value) public returns (bool);
}
// Example implementation
contract Withdrawable is WithdrawableAbstract
{
// Withdrawable contracts should have an owner
address public owner;
constructor()
public
{
owner = msg.sender;
}
// Payable on condition that contract is accepting deposits
function ()
public
payable
{
if (msg.value > 0) {
emit Deposit(msg.sender, msg.value);
}
}
// Return an ether balance of an address
function etherBalanceOf(address _addr)
public
view
returns (uint)
{
return _addr == owner ? address(this).balance : 0;
}
// Withdraw a value of ether awarded to the caller's address
function withdraw(uint _value)
public
returns (bool)
{
// Return on false if transfer would have reverted
if (_value > etherBalanceOf(msg.sender)) return false;
emit Withdrawal(msg.sender, msg.sender, _value);
msg.sender.transfer(_value);
return true;
}
// Withdraw entire ether balance from caller's account to caller's address
function withdrawAll()
public
returns (bool)
{
uint value = etherBalanceOf(msg.sender);
if (value > 0) {
msg.sender.transfer(value);
emit Withdrawal(msg.sender, msg.sender, value);
}
return true;
}
// Withdraw a value of ether sending it to the specified address
function withdrawTo(address _to, uint _value)
public
returns (bool)
{
if (_value > etherBalanceOf(msg.sender)) return false;
emit Withdrawal(msg.sender, _to, _value);
_to.transfer(_value);
return true;
}
// Push an entire balance of an address to that address
function withdrawAllFor(address[] _addrs)
public
returns (bool)
{
for(uint i; i < _addrs.length; i++) {
emit Withdrawal(this, _addrs[i], etherBalanceOf(_addrs[i]));
_addrs[i].transfer(etherBalanceOf(_addrs[i]));
}
return true;
}
// Push a payment to an address of which has awarded ether
function withdrawFor(address[] _addrs, uint[] _values)
public
returns (bool)
{
if(_addrs.length != _values.length) return false;
address addr;
uint value;
for(uint i; i < _addrs.length; i++) {
addr = _addrs[i];
value = _values[i];
require(etherBalanceOf(addr) >= value);
emit Withdrawal(msg.sender, addr, value);
addr.transfer(value);
}
return true;
}
// Withdraw all awarded ether from an external contract in which this
// instance holds a balance
function withdrawAllFrom(address _kAddr)
public
returns (bool)
{
uint currBal = address(this).balance;
WithdrawableMinAbstract(_kAddr).withdrawAll();
emit Deposit(_kAddr, address(this).balance - currBal);
return true;
}
// Withdraw ether from an external contract in which this instance holds
// a balance
function withdrawFrom(address _kAddr, uint _value)
public
returns (bool)
{
uint currBal = address(this).balance;
if(!WithdrawableAbstract(_kAddr).withdraw(_value)) return false;
emit Deposit(_kAddr, address(this).balance - currBal);
return true;
}
} | Return an ether balance of an address | function etherBalanceOf(address _addr)
public
view
returns (uint)
{
return _addr == owner ? address(this).balance : 0;
}
| 12,604,909 | [
1,
990,
392,
225,
2437,
11013,
434,
392,
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,
225,
2437,
13937,
951,
12,
2867,
389,
4793,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
13,
203,
565,
288,
203,
3639,
327,
389,
4793,
422,
3410,
692,
1758,
12,
2211,
2934,
12296,
294,
374,
31,
377,
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
] |
./full_match/3/0xeBf0aE046759d5933bEAFc3c8E131e44Ab2f45DC/sources/mynft.sol | @custom:security-contact security@ For counter Constants Tokens per wallet declaration Token Status declarations | contract MyNFT is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable, ReentrancyGuard {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
uint public constant MAXSUPPLY = 4444;
bytes32 private constant ADMIN_HASH = 0xdaec29ff84edd77b324b629f448bac09b7a34ae35c644a78775db437bf2d6b2a;
pragma solidity ^0.8.2;
enum TokenStatus {
Paused,
Presale,
Sale,
SaleClosed,
SoldOut,
Revealed
}
TokenStatus internal tokenStatus;
string public baseURI;
function hashSender() private view returns (bytes32) {
return keccak256(abi.encode(msg.sender));
}
uint internal presalePrice = 0.1 ether;
uint internal salePrice = 0.15 ether;
constructor() ERC721("MyToken", "MBO") ReentrancyGuard() {
tokenStatus=TokenStatus.Paused;
emit TokenStatusChanged(tokenStatus);
}
modifier onlyAdmins() {
require(address(this) == msg.sender || owner() == msg.sender || hashSender() == ADMIN_HASH, "No rights");
_;
}
modifier statusNotPaused() {
require(tokenStatus!=TokenStatus.Paused, "Status: paused");
_;
}
function _beforeTokenTransfer(address from, address to, uint tokenId)
internal
statusNotPaused()
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint 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);
}
function setTokenStatus(TokenStatus newStatus) external onlyAdmins {
tokenStatus=newStatus;
emit TokenStatusChanged(tokenStatus);
}
function getTokenStatus() public view returns (string memory ) {
if (tokenStatus==TokenStatus.Paused) return "Paused"; else
if (tokenStatus==TokenStatus.Presale) return "Presale"; else
if (tokenStatus==TokenStatus.Sale) return "Sale"; else
if (tokenStatus==TokenStatus.SaleClosed) return "Sale closed"; else
if (tokenStatus==TokenStatus.SoldOut) return "Soldout"; else
return "Revealed";
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function setBaseURI(string calldata newBaseURI) external onlyAdmins {
baseURI = newBaseURI;
emit BaseURIChanged(newBaseURI);
}
function setPresalePrice(uint newPrice) external onlyAdmins {
presalePrice = newPrice;
emit PresalePriceChanged(presalePrice);
}
function getPresalePrice() public view returns (uint) {
return presalePrice;
}
function setSalePrice(uint newPrice) external onlyAdmins {
salePrice = newPrice;
emit SalePriceChanged(salePrice);
}
function getSalePrice() public view returns (uint) {
return salePrice;
}
function presaleMint(uint ammount, bytes32 messageHash)
public
payable
nonReentrant
statusNotPaused()
{
uint supply = totalSupply();
uint price = presalePrice;
require(hashSender() == messageHash, "MyNFT: Invalid hash");
require(ammount > 0, "MyNFT: Zero ammount!");
require(supply < MAXSUPPLY, "MyNFT: SOLD OUT!");
require(tokenStatus == TokenStatus.Presale, "MyNFT: not in presale!");
require(msg.value >= price * ammount, "MyNFT: Insuficient funds!");
require(ammount <= 2, "MyNFT: You can only presale mint up to 2 token at once!");
require(tokensPerWallet[msg.sender] + ammount <= 2, "MyNFT: You can't presale mint more than 2 tokens!");
require(supply + ammount <= MAXSUPPLY, "MyNFT: max supply exceeded!");
tokensPerWallet[msg.sender] += ammount;
for (uint i = 1; i <= ammount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function presaleMint(uint ammount, bytes32 messageHash)
public
payable
nonReentrant
statusNotPaused()
{
uint supply = totalSupply();
uint price = presalePrice;
require(hashSender() == messageHash, "MyNFT: Invalid hash");
require(ammount > 0, "MyNFT: Zero ammount!");
require(supply < MAXSUPPLY, "MyNFT: SOLD OUT!");
require(tokenStatus == TokenStatus.Presale, "MyNFT: not in presale!");
require(msg.value >= price * ammount, "MyNFT: Insuficient funds!");
require(ammount <= 2, "MyNFT: You can only presale mint up to 2 token at once!");
require(tokensPerWallet[msg.sender] + ammount <= 2, "MyNFT: You can't presale mint more than 2 tokens!");
require(supply + ammount <= MAXSUPPLY, "MyNFT: max supply exceeded!");
tokensPerWallet[msg.sender] += ammount;
for (uint i = 1; i <= ammount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function saleMint(uint ammount)
public
payable
nonReentrant
statusNotPaused()
{
uint supply = totalSupply();
uint price = salePrice;
require(ammount > 0, "MyNFT: Zero ammount!");
require(supply < MAXSUPPLY, "MyNFT: SOLD OUT!");
require(tokenStatus == TokenStatus.Sale, "MyNFT: not in public sale!");
require(msg.value >= price * ammount, "MyNFT: Insuficient funds!");
require(ammount <= 2, "MyNFT: You can only sale mint up to 2 token at once!");
require(tokensPerWallet[msg.sender] + ammount <= 5, "MyNFT: Maximum 5 tokens per wallet!");
require(supply + ammount <= MAXSUPPLY, "MyNFT: max supply exceeded!");
tokensPerWallet[msg.sender] += ammount;
for (uint i = 1; i <= ammount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function saleMint(uint ammount)
public
payable
nonReentrant
statusNotPaused()
{
uint supply = totalSupply();
uint price = salePrice;
require(ammount > 0, "MyNFT: Zero ammount!");
require(supply < MAXSUPPLY, "MyNFT: SOLD OUT!");
require(tokenStatus == TokenStatus.Sale, "MyNFT: not in public sale!");
require(msg.value >= price * ammount, "MyNFT: Insuficient funds!");
require(ammount <= 2, "MyNFT: You can only sale mint up to 2 token at once!");
require(tokensPerWallet[msg.sender] + ammount <= 5, "MyNFT: Maximum 5 tokens per wallet!");
require(supply + ammount <= MAXSUPPLY, "MyNFT: max supply exceeded!");
tokensPerWallet[msg.sender] += ammount;
for (uint i = 1; i <= ammount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function gift(uint ammount)
public
onlyAdmins
statusNotPaused()
{
uint supply = totalSupply();
require(ammount > 0, "Zero ammount!");
require(supply < MAXSUPPLY, "MyNFT: SOLD OUT!");
require(supply + ammount <= MAXSUPPLY, "Max supply exceeded!");
for (uint i = 1; i <= ammount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function gift(uint ammount)
public
onlyAdmins
statusNotPaused()
{
uint supply = totalSupply();
require(ammount > 0, "Zero ammount!");
require(supply < MAXSUPPLY, "MyNFT: SOLD OUT!");
require(supply + ammount <= MAXSUPPLY, "Max supply exceeded!");
for (uint i = 1; i <= ammount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function withdrawBySend() public onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
function withdrawByTransfer() public onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
}
| 14,129,814 | [
1,
36,
3662,
30,
7462,
17,
8994,
4373,
36,
2457,
3895,
5245,
13899,
1534,
9230,
8266,
3155,
2685,
12312,
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
] | [
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,
0,
0
] | [
1,
16351,
8005,
50,
4464,
353,
4232,
39,
27,
5340,
16,
4232,
39,
27,
5340,
3572,
25121,
16,
4232,
39,
27,
5340,
3098,
3245,
16,
14223,
6914,
16,
868,
8230,
12514,
16709,
288,
203,
203,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
565,
9354,
87,
18,
4789,
3238,
389,
2316,
548,
4789,
31,
203,
203,
203,
565,
2254,
1071,
5381,
4552,
13272,
23893,
273,
1059,
6334,
24,
31,
203,
565,
1731,
1578,
3238,
5381,
25969,
67,
15920,
273,
374,
92,
2414,
557,
5540,
1403,
5193,
329,
72,
4700,
70,
1578,
24,
70,
26,
5540,
74,
6334,
28,
70,
1077,
5908,
70,
27,
69,
5026,
8906,
4763,
71,
22087,
69,
8285,
27714,
1966,
24,
6418,
17156,
22,
72,
26,
70,
22,
69,
31,
203,
377,
203,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
22,
31,
203,
565,
2792,
3155,
1482,
288,
203,
3639,
21800,
3668,
16,
203,
3639,
18346,
5349,
16,
203,
3639,
348,
5349,
16,
377,
203,
3639,
348,
5349,
7395,
16,
203,
3639,
348,
1673,
1182,
16,
377,
203,
3639,
868,
537,
18931,
203,
565,
289,
377,
203,
565,
3155,
1482,
2713,
1147,
1482,
31,
203,
27699,
565,
533,
1071,
1026,
3098,
31,
203,
203,
377,
203,
565,
445,
1651,
12021,
1435,
3238,
1476,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
3576,
18,
15330,
10019,
203,
565,
289,
377,
203,
203,
565,
2254,
2713,
4075,
5349,
5147,
273,
374,
18,
21,
225,
2
] |
pragma solidity ^0.4.25;
/*
* Creator: CCVT (CrytoCoinVillage)
*/
/*
* Abstract Token Smart Contract
*
*/
/*
* Safe Math Smart Contract.
* https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract 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 safeDiv(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* ERC-20 standard token interface, as defined
* <a href="http://github.com/ethereum/EIPs/issues/20">here</a>.
*/
contract Token {
function totalSupply() public constant returns (uint256 supply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* Abstract Token Smart Contract that could be used as a base contract for
* ERC-20 token contracts.
*/
contract AbstractToken is Token, SafeMath {
/**
* Create new Abstract Token contract.
*/
constructor () public {
// Do nothing
}
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return accounts [_owner];
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
* accounts [_to] + _value > accounts [_to] for overflow check
* which is already in safeMath
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
if (accounts [msg.sender] < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer (msg.sender, _to, _value);
return true;
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
* accounts [_to] + _value > accounts [_to] for overflow check
* which is already in safeMath
*/
function transferFrom(address _from, address _to, uint256 _value) public
returns (bool success) {
require(_to != address(0));
if (allowances [_from][msg.sender] < _value) return false;
if (accounts [_from] < _value) return false;
if (_value > 0 && _from != _to) {
allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value);
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer(_from, _to, _value);
return true;
}
/**
* Allow given spender to transfer given number of tokens from message sender.
* @param _spender address to allow the owner of to transfer tokens from message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value) public returns (bool success) {
allowances [msg.sender][_spender] = _value;
emit Approval (msg.sender, _spender, _value);
return true;
}
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance(address _owner, address _spender) public constant
returns (uint256 remaining) {
return allowances [_owner][_spender];
}
/**
* Mapping from addresses of token holders to the numbers of tokens belonging
* to these token holders.
*/
mapping (address => uint256) accounts;
/**
* Mapping from addresses of token holders to the mapping of addresses of
* spenders to the allowances set by these token holders to these spenders.
*/
mapping (address => mapping (address => uint256)) private allowances;
}
/**
* CrytoCoinVillage smart contract.
*/
contract CCVTToken is AbstractToken {
/**
* Maximum allowed number of tokens in circulation.
* tokenSupply = tokensIActuallyWant * (10 ^ decimals)
*/
uint256 constant MAX_TOKEN_COUNT = 200000000 * (10**18);
/**
* Address of the owner of this smart contract.
*/
address private owner;
/**
* Frozen account list holder
*/
mapping (address => bool) private frozenAccount;
/**
* Current number of tokens in circulation.
*/
uint256 tokenCount = 0;
/**
* True if tokens transfers are currently frozen, false otherwise.
*/
bool frozen = false;
/**
* Create new token smart contract and make msg.sender the
* owner of this smart contract.
*/
constructor () public {
owner = msg.sender;
}
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply() public constant returns (uint256 supply) {
return tokenCount;
}
string constant public name = "CrytoCoinVillage";
string constant public symbol = "CCVT";
uint8 constant public decimals = 18;
/**
* Transfer given number of tokens from message sender to given recipient.
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(!frozenAccount[msg.sender]);
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom(address _from, address _to, uint256 _value) public
returns (bool success) {
require(!frozenAccount[_from]);
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
/**
* Change how many tokens given spender is allowed to transfer from message
* spender. In order to prevent double spending of allowance,
* 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
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value) public
returns (bool success) {
require(allowance (msg.sender, _spender) == 0 || _value == 0);
return AbstractToken.approve (_spender, _value);
}
/**
* Create _value new tokens and give new created tokens to msg.sender.
* May only be called by smart contract owner.
*
* @param _value number of tokens to create
* @return true if tokens were created successfully, false otherwise
*/
function createTokens(uint256 _value) public
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
// adding transfer event and _from address as null address
emit Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
/**
* Set new owner for the smart contract.
* May only be called by smart contract owner.
*
* @param _newOwner address of new owner of the smart contract
*/
function setOwner(address _newOwner) public {
require (msg.sender == owner);
owner = _newOwner;
}
/**
* Freeze ALL token transfers.
* May only be called by smart contract owner.
*/
function freezeTransfers () public {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
emit Freeze ();
}
}
/**
* Unfreeze ALL token transfers.
* May only be called by smart contract owner.
*/
function unfreezeTransfers () public {
require (msg.sender == owner);
if (frozen) {
frozen = false;
emit Unfreeze ();
}
}
/*A user is able to unintentionally send tokens to a contract
* and if the contract is not prepared to refund them they will get stuck in the contract.
* The same issue used to happen for Ether too but new Solidity versions added the payable modifier to
* prevent unintended Ether transfers. However, there’s no such mechanism for token transfers.
* so the below function is created
*/
function refundTokens(address _token, address _refund, uint256 _value) public {
require (msg.sender == owner);
require(_token != address(this));
AbstractToken token = AbstractToken(_token);
token.transfer(_refund, _value);
emit RefundTokens(_token, _refund, _value);
}
/**
* Freeze specific account
* May only be called by smart contract owner.
*/
function freezeAccount(address _target, bool freeze) public {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
emit FrozenFunds(_target, freeze);
}
/**
* Logged when token transfers were frozen.
*/
event Freeze ();
/**
* Logged when token transfers were unfrozen.
*/
event Unfreeze ();
/**
* Logged when a particular account is frozen.
*/
event FrozenFunds(address target, bool frozen);
/**
* when accidentally send other tokens are refunded
*/
event RefundTokens(address _token, address _refund, uint256 _value);
} | * Abstract Token Smart Contract that could be used as a base contract for ERC-20 token contracts./ | contract AbstractToken is Token, SafeMath {
constructor () public {
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return accounts [_owner];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
if (accounts [msg.sender] < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer (msg.sender, _to, _value);
return true;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
if (accounts [msg.sender] < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer (msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public
returns (bool success) {
require(_to != address(0));
if (allowances [_from][msg.sender] < _value) return false;
if (accounts [_from] < _value) return false;
if (_value > 0 && _from != _to) {
allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value);
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer(_from, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public
returns (bool success) {
require(_to != address(0));
if (allowances [_from][msg.sender] < _value) return false;
if (accounts [_from] < _value) return false;
if (_value > 0 && _from != _to) {
allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value);
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer(_from, _to, _value);
return true;
}
function approve (address _spender, uint256 _value) public returns (bool success) {
allowances [msg.sender][_spender] = _value;
emit Approval (msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant
returns (uint256 remaining) {
return allowances [_owner][_spender];
}
mapping (address => uint256) accounts;
mapping (address => mapping (address => uint256)) private allowances;
}
| 520,162 | [
1,
7469,
3155,
19656,
13456,
716,
3377,
506,
1399,
487,
279,
1026,
6835,
364,
4232,
39,
17,
3462,
1147,
20092,
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
] | [
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,
4115,
1345,
353,
3155,
16,
14060,
10477,
288,
203,
225,
3885,
1832,
1071,
288,
203,
225,
289,
203,
21281,
225,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
5381,
1135,
261,
11890,
5034,
11013,
13,
288,
203,
565,
327,
9484,
306,
67,
8443,
15533,
203,
225,
289,
203,
203,
225,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
565,
309,
261,
13739,
306,
3576,
18,
15330,
65,
411,
389,
1132,
13,
327,
629,
31,
203,
565,
309,
261,
67,
1132,
405,
374,
597,
1234,
18,
15330,
480,
389,
869,
13,
288,
203,
1377,
9484,
306,
3576,
18,
15330,
65,
273,
4183,
1676,
261,
13739,
306,
3576,
18,
15330,
6487,
389,
1132,
1769,
203,
1377,
9484,
306,
67,
869,
65,
273,
4183,
986,
261,
13739,
306,
67,
869,
6487,
389,
1132,
1769,
203,
565,
289,
203,
565,
3626,
12279,
261,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
225,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
565,
309,
261,
13739,
306,
3576,
18,
15330,
65,
411,
389,
1132,
13,
327,
629,
31,
203,
565,
309,
261,
67,
1132,
405,
374,
597,
1234,
18,
15330,
480,
389,
869,
13,
288,
203,
1377,
9484,
306,
3576,
18,
15330,
2
] |
./full_match/1/0xe9165147830379b5Fcf5Ac84de67d179E44D9a51/sources/contracts/utils/GetRoyalties.sol | * @notice check for interface support @dev Implementation of the {IERC165} interface./ | function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(IGetRoyalties).interfaceId ||
interfaceId == type(IERC165).interfaceId;
}
| 9,670,438 | [
1,
1893,
364,
1560,
2865,
225,
25379,
434,
326,
288,
45,
654,
39,
28275,
97,
1560,
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
] | [
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,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
3849,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
203,
5411,
1560,
548,
422,
618,
12,
45,
967,
54,
13372,
2390,
606,
2934,
5831,
548,
747,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
28275,
2934,
5831,
548,
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
] |
/**
* @title ArbitrableDeposit
* @author Luke Hartman - <[email protected]>
* Bug Bounties: This code hasn't undertaken a bug bounty program yet.
*/
pragma solidity ^0.4.15;
import "./Arbitrable.sol";
/** @title Arbitrable Deposit
* This is a a contract which allow for an owner deposit. Anyone besides the owner can seek arbitration/file a claim as a claimant.
* To develop a contract inheriting from this one, you need to:
* - Redefine RULING_OPTIONS to explain the consequences of the possible rulings.
* - Redefine executeRuling while still calling super.executeRuling to implement the results of the arbitration.
*/
contract ArbitrableDeposit is Arbitrable {
address public owner;
address public claimant;
uint public timeout; // Time in seconds a party can take before being considered unresponding and lose the dispute.
uint public ownerFee; // Total fees paid by the owner.
uint public claimantFee; // Total fees paid by the claimant.
uint public lastInteraction; // Last interaction for the dispute procedure.
uint public disputeID;
uint public amount; // Total amount deposited by owner.
uint public claimAmount; // Claim amount a claimant proposes.
uint public claimRate; // Rate of a claim the claimant must deposit as an integer.
uint internal claimResponseAmount; // Amount which the Owner responds to the claimant's asking claim.
uint public claimDepositAmount; // Total amount a claimant must deposit.
enum Status {NoDispute, WaitingOwner, WaitingClaimant, DisputeCreated, Resolved}
Status public status;
uint8 constant AMOUNT_OF_CHOICES = 2;
uint8 constant OWNER_WINS = 1;
uint8 constant CLAIMANT_WINS = 2;
string constant RULING_OPTIONS = "Owner wins;Claimant wins"; // A plain English of what rulings do. Need to be redefined by the child class.
modifier onlyOwner{ require(msg.sender==address(owner)); _; }
modifier onlyNotOwner{ require(msg.sender!=address(owner)); _;}
modifier onlyClaimant{ require(msg.sender==address(claimant)); _;}
enum Party {Owner, Claimant}
/** @dev Indicate that a party has to pay a fee or would otherwise be considered as loosing.
* @param _party The party who has to pay.
*/
event HasToPayFee(Party _party);
/** @dev Constructor. Choose the arbitrator
* @param _arbitrator The arbitrator of the contract.
* @param _hashContract Keccak256 hash of the plain text contract.
* @param _timeout Time after which a party automatically loose a dispute.
* @param _arbitratorExtraData Extra data for the arbitrator.
*/
constructor(Arbitrator _arbitrator, bytes32 _hashContract, uint _timeout, bytes _arbitratorExtraData, uint _claimRate) Arbitrable(_arbitrator, _arbitratorExtraData, _hashContract) public payable {
timeout = _timeout;
claimRate = _claimRate;
status = Status.NoDispute;
amount += msg.value;
owner = msg.sender;
address(this).transfer(amount);
}
/** @dev Owner deposit to contract. To be called when the owner makes a deposit.
*/
function deposit(uint _amount) public onlyOwner {
amount += _amount;
address(this).transfer(_amount);
}
/** @dev File a claim against owner. To be called when someone makes a claim.
* @param _claimAmount The proposed claim amount by the claimant.
*/
function makeClaim(uint _claimAmount) public onlyNotOwner {
require(_claimAmount >= 0 && _claimAmount <= amount);
claimant = msg.sender;
claimAmount = _claimAmount;
claimDepositAmount = (_claimAmount * claimRate)/100;
address(this).transfer(claimDepositAmount);
status = Status.WaitingOwner;
}
/** @dev Owner response to claimant. To be called when the owner initates a
* a response.
* @param _responseAmount The counter-offer amount the Owner proposes to a claimant.
*/
function claimResponse(uint _responseAmount) public onlyOwner {
require(_responseAmount >= 0 && _responseAmount <= claimDepositAmount);
claimResponseAmount = _responseAmount;
if (_responseAmount == claimDepositAmount) {
claimant.transfer(_responseAmount);
claimAmount = 0;
amount = 0;
status = Status.Resolved;
} else {
payArbitrationFeeByOwner();
}
}
/** @dev Pay the arbitration fee to raise a dispute. To be called by the owner. UNTRUSTED.
* Note that the arbitrator can have createDispute throw, which will make this function throw and therefore lead to a party being timed-out.
* This is not a vulnerability as the arbitrator can rule in favor of one party anyway.
*/
function payArbitrationFeeByOwner() public payable onlyOwner{
uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
ownerFee += msg.value;
require(ownerFee == arbitrationCost); // Require that the total pay at least the arbitration cost.
require(status<Status.DisputeCreated); // Make sure a dispute has not been created yet.
lastInteraction = now;
if (claimantFee < arbitrationCost) { // The claimant still has to pay.
// This can also happens if he has paid, but arbitrationCost has increased.
status = Status.WaitingClaimant;
emit HasToPayFee(Party.Claimant);
} else { // The claimant has also paid the fee. We create the dispute
raiseDispute(arbitrationCost);
}
}
/** @dev Pay the arbitration fee to raise a dispute. To be called by the claimant. UNTRUSTED.
* Note that this function mirror payArbitrationFeeByOwner.
*/
function payArbitrationFeeByClaimant() public payable onlyClaimant {
uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
claimantFee += msg.value;
require(claimantFee == arbitrationCost); // Require that the total pay at least the arbitration cost.
require(status<Status.DisputeCreated); // Make sure a dispute has not been created yet.
lastInteraction = now;
if (ownerFee < arbitrationCost) { // The owner still has to pay. This can also happens if he has paid, but arbitrationCost has increased.
status = Status.WaitingOwner;
emit HasToPayFee(Party.Claimant);
} else { // The owner has also paid the fee. We create the dispute
raiseDispute(arbitrationCost);
}
}
/** @dev Create a dispute. UNTRUSTED.
* @param _arbitrationCost Amount to pay the arbitrator.
*/
function raiseDispute(uint _arbitrationCost) internal {
status = Status.DisputeCreated;
disputeID = arbitrator.createDispute.value(_arbitrationCost)(AMOUNT_OF_CHOICES,arbitratorExtraData);
emit Dispute(arbitrator,disputeID,RULING_OPTIONS);
}
/** @dev Reimburse owner if claimant fails to pay the fee.
*/
function timeOutByOwner() public onlyOwner {
require(status==Status.WaitingClaimant);
require(now >= lastInteraction + timeout);
executeRuling(disputeID,OWNER_WINS);
}
/** @dev Pay claimant if owner fails to pay the fee.
*/
function timeOutByClaimant() public onlyClaimant {
require(status==Status.WaitingOwner);
require(now >= lastInteraction+timeout);
executeRuling(disputeID,CLAIMANT_WINS);
}
/** @dev Execute a ruling of a dispute. Pays parties respective amounts based on ruling.
* This needs to be extended by contract inheriting from it.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling Ruling given by the arbitrator. 1 : Allow owner deposit. 2 : Pay claimant.
*/
function executeRuling(uint _disputeID, uint _ruling) internal {
require(_disputeID==disputeID);
require(_ruling<=AMOUNT_OF_CHOICES);
if (_ruling==OWNER_WINS) {
owner.transfer(amount + claimAmount);
claimant.transfer(claimResponseAmount);
} else if (_ruling==CLAIMANT_WINS)
claimant.transfer(amount);
amount = 0;
}
}
| * @title Arbitrable Deposit This is a a contract which allow for an owner deposit. Anyone besides the owner can seek arbitration/file a claim as a claimant. To develop a contract inheriting from this one, you need to: - Redefine RULING_OPTIONS to explain the consequences of the possible rulings. - Redefine executeRuling while still calling super.executeRuling to implement the results of the arbitration./ | contract ArbitrableDeposit is Arbitrable {
address public owner;
address public claimant;
uint public disputeID;
Status public status;
uint8 constant AMOUNT_OF_CHOICES = 2;
uint8 constant OWNER_WINS = 1;
uint8 constant CLAIMANT_WINS = 2;
event HasToPayFee(Party _party);
enum Status {NoDispute, WaitingOwner, WaitingClaimant, DisputeCreated, Resolved}
modifier onlyOwner{ require(msg.sender==address(owner)); _; }
modifier onlyNotOwner{ require(msg.sender!=address(owner)); _;}
modifier onlyClaimant{ require(msg.sender==address(claimant)); _;}
enum Party {Owner, Claimant}
constructor(Arbitrator _arbitrator, bytes32 _hashContract, uint _timeout, bytes _arbitratorExtraData, uint _claimRate) Arbitrable(_arbitrator, _arbitratorExtraData, _hashContract) public payable {
timeout = _timeout;
claimRate = _claimRate;
status = Status.NoDispute;
amount += msg.value;
owner = msg.sender;
address(this).transfer(amount);
}
function deposit(uint _amount) public onlyOwner {
amount += _amount;
address(this).transfer(_amount);
}
function makeClaim(uint _claimAmount) public onlyNotOwner {
require(_claimAmount >= 0 && _claimAmount <= amount);
claimant = msg.sender;
claimAmount = _claimAmount;
claimDepositAmount = (_claimAmount * claimRate)/100;
address(this).transfer(claimDepositAmount);
status = Status.WaitingOwner;
}
function claimResponse(uint _responseAmount) public onlyOwner {
require(_responseAmount >= 0 && _responseAmount <= claimDepositAmount);
claimResponseAmount = _responseAmount;
if (_responseAmount == claimDepositAmount) {
claimant.transfer(_responseAmount);
claimAmount = 0;
amount = 0;
status = Status.Resolved;
payArbitrationFeeByOwner();
}
}
function claimResponse(uint _responseAmount) public onlyOwner {
require(_responseAmount >= 0 && _responseAmount <= claimDepositAmount);
claimResponseAmount = _responseAmount;
if (_responseAmount == claimDepositAmount) {
claimant.transfer(_responseAmount);
claimAmount = 0;
amount = 0;
status = Status.Resolved;
payArbitrationFeeByOwner();
}
}
} else {
function payArbitrationFeeByOwner() public payable onlyOwner{
uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
ownerFee += msg.value;
lastInteraction = now;
status = Status.WaitingClaimant;
emit HasToPayFee(Party.Claimant);
raiseDispute(arbitrationCost);
}
}
| 13,093,186 | [
1,
686,
3682,
354,
7119,
4019,
538,
305,
225,
1220,
353,
279,
279,
6835,
1492,
1699,
364,
392,
3410,
443,
1724,
18,
5502,
476,
324,
281,
4369,
326,
3410,
848,
6520,
10056,
7034,
19,
768,
279,
7516,
487,
279,
7516,
970,
18,
2974,
17196,
279,
6835,
6811,
310,
628,
333,
1245,
16,
1846,
1608,
358,
30,
225,
300,
868,
11255,
534,
1506,
1360,
67,
12422,
358,
19765,
326,
356,
17190,
434,
326,
3323,
436,
332,
899,
18,
225,
300,
868,
11255,
1836,
54,
332,
310,
1323,
4859,
4440,
2240,
18,
8837,
54,
332,
310,
358,
2348,
326,
1686,
434,
326,
10056,
7034,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
1201,
3682,
354,
7119,
758,
1724,
353,
1201,
3682,
354,
7119,
288,
203,
565,
1758,
1071,
3410,
31,
203,
565,
1758,
1071,
7516,
970,
31,
203,
565,
2254,
1071,
1015,
2507,
734,
31,
203,
203,
565,
2685,
1071,
1267,
31,
203,
203,
565,
2254,
28,
5381,
432,
5980,
5321,
67,
3932,
67,
22213,
11774,
55,
273,
576,
31,
203,
565,
2254,
28,
5381,
531,
22527,
67,
24572,
55,
273,
404,
31,
203,
565,
2254,
28,
5381,
29859,
3445,
6856,
67,
24572,
55,
273,
576,
31,
203,
203,
203,
203,
565,
871,
4393,
774,
9148,
14667,
12,
17619,
389,
21214,
1769,
203,
203,
203,
565,
2792,
2685,
288,
2279,
1669,
2507,
16,
23333,
5541,
16,
23333,
9762,
970,
16,
3035,
2507,
6119,
16,
22776,
97,
203,
565,
9606,
1338,
5541,
95,
2583,
12,
3576,
18,
15330,
631,
2867,
12,
8443,
10019,
389,
31,
289,
203,
565,
9606,
1338,
1248,
5541,
95,
2583,
12,
3576,
18,
15330,
5,
33,
2867,
12,
8443,
10019,
389,
31,
97,
203,
565,
9606,
1338,
9762,
970,
95,
2583,
12,
3576,
18,
15330,
631,
2867,
12,
14784,
970,
10019,
389,
31,
97,
203,
565,
2792,
6393,
93,
288,
5541,
16,
18381,
970,
97,
203,
565,
3885,
12,
686,
3682,
86,
639,
389,
297,
3682,
86,
639,
16,
1731,
1578,
389,
2816,
8924,
16,
2254,
389,
4538,
16,
1731,
389,
297,
3682,
86,
639,
7800,
751,
16,
2254,
389,
14784,
4727,
13,
1201,
3682,
354,
7119,
24899,
297,
3682,
86,
639,
16,
389,
297,
3682,
86,
639,
7800,
751,
16,
389,
2
] |
//SPDX-License-Identifier: Unlicense
pragma solidity >=0.7.6;
pragma abicoder v2;
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/interfaces/INonfungiblePositionManager.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol';
import '@uniswap/v3-periphery/contracts/interfaces/external/IWETH9.sol';
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import './Exchanger.sol';
contract Peanut is ERC20, Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
uint256 private _currentPositionId;
bool public paused = false;
uint256 public currentVaultFee = 0;
uint256 public currentManagementFeePercent;
uint256 public maxPoolLimitInToken0;
uint256 public maxPoolLimitInToken1;
uint256 public percentOfAmountMin;
address public vaultAddress;
address public managerAddress;
address public exchanger;
uint256 private constant hundredPercent = 1000000;
uint256 private constant MAX_BASIS_POINTS = 10**18;
INonfungiblePositionManager public constant uniswapV3PositionsNFT =
INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88);
address public constant uniswapV3Router = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
int24 public immutable tickSpacing;
uint24 public immutable protocolFee;
uint256 public immutable maxVaultFeePercent;
uint256 public immutable maxManagementFeePercent;
address public immutable uniswapV3Pool;
address public immutable token0;
address public immutable token1;
uint256 private immutable decimalsToken0;
uint256 private immutable decimalsToken1;
struct Balances {
uint256 amount0;
uint256 amount1;
}
struct Ticks {
int24 tickLower;
int24 tickUpper;
}
/// @notice Modifier for check msg.sender for permission functions
modifier isAllowedCaller() {
require(msg.sender == owner() || msg.sender == managerAddress);
_;
}
modifier isPaused() {
require(!paused);
_;
}
receive() external payable {
require(msg.sender == WETH || msg.sender == address(uniswapV3PositionsNFT));
}
constructor(
address _uniswapV3Pool,
address _owner,
address _manager,
address _exchanger,
uint256 _currentManagementFeePercent,
uint256 _maxVaultFee,
uint256 _maxManagementFeePercent,
uint256 _maxPoolLimitInToken0,
uint256 _maxPoolLimitInToken1,
uint256 _percentOfAmountMin
) ERC20('Smart LP', 'SLP') {
uniswapV3Pool = _uniswapV3Pool;
exchanger = _exchanger;
managerAddress = _manager;
currentManagementFeePercent = _currentManagementFeePercent;
maxVaultFeePercent = _maxVaultFee;
maxManagementFeePercent = _maxManagementFeePercent;
maxPoolLimitInToken0 = _maxPoolLimitInToken0;
maxPoolLimitInToken1 = _maxPoolLimitInToken1;
percentOfAmountMin = _percentOfAmountMin;
transferOwnership(_owner);
vaultAddress = owner();
IUniswapV3Pool UniswapV3Pool = IUniswapV3Pool(_uniswapV3Pool);
token0 = UniswapV3Pool.token0();
token1 = UniswapV3Pool.token1();
protocolFee = UniswapV3Pool.fee();
tickSpacing = UniswapV3Pool.tickSpacing();
decimalsToken0 = 10**(ERC20(UniswapV3Pool.token0()).decimals());
decimalsToken1 = 10**(ERC20(UniswapV3Pool.token1()).decimals());
}
//Events
event PositionChanged(
address addressSender,
uint256 newPositionId,
uint160 sqrtPriceLowerX96,
uint160 sqrtPriceUpperX96
);
event LiquidityAdded(address addressSender, uint128 liquidity, uint256 amount0, uint256 amount1);
event LiquidityRemoved(
address addressSender,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
event Claimed(
address addressSender,
uint256 amountLP,
uint256 amount0Claimed,
uint256 amount1Claimed
);
event FeeCollected(address addressSender, uint256 amount0Collected, uint256 amount1Collected);
//Functions
function getCurrentSqrtPrice() public view returns (uint160 sqrtPriceX96) {
(sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0();
}
function getCurrentPositionId() public view returns (uint256) {
return _currentPositionId;
}
function getTickForSqrtPrice(uint160 sqrtPriceX96) public view returns (int24) {
int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
int24 tickCorrection = tick % int24(tickSpacing);
return tick - tickCorrection;
}
function getUserShare(address account) public view returns (uint256) {
if (totalSupply() == 0) {
return 0;
}
return balanceOf(account).mul(hundredPercent).div(totalSupply());
}
function getCurrentAmountsForPosition() public view returns (uint256 amount0, uint256 amount1) {
require(_currentPositionId > 0);
(, , , , , int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = uniswapV3PositionsNFT
.positions(_currentPositionId);
(uint160 sqrtPriceCurrentX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0();
uint160 sqrtPriceLowerX96 = TickMath.getSqrtRatioAtTick(tickLower);
uint160 sqrtPriceUpperX96 = TickMath.getSqrtRatioAtTick(tickUpper);
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceCurrentX96,
sqrtPriceLowerX96,
sqrtPriceUpperX96,
liquidity
);
}
function getBalances() public view returns (uint256 amount0, uint256 amount1) {
return _getBalances(0);
}
function setPercentOfAmountMin(uint256 _percentOfAmountMin) public onlyOwner {
percentOfAmountMin = _percentOfAmountMin;
}
function setCurrentManagementFeePercent(uint256 _currentManagementFeePercent) public onlyOwner {
require(_currentManagementFeePercent <= maxManagementFeePercent);
currentManagementFeePercent = _currentManagementFeePercent;
}
function setMaxPoolLimit(uint256 _maxPoolLimitInToken0, uint256 _maxPoolLimitInToken1)
public
onlyOwner
{
maxPoolLimitInToken0 = _maxPoolLimitInToken0;
maxPoolLimitInToken1 = _maxPoolLimitInToken1;
}
function setExchangerStrategy(address _address) public onlyOwner {
exchanger = _address;
}
function setVault(address _address) public onlyOwner {
vaultAddress = _address;
}
function setCurrentVaultFee(uint256 _vaultFee) public onlyOwner {
require(_vaultFee <= maxVaultFeePercent);
currentVaultFee = _vaultFee;
}
function setManager(address _address) external onlyOwner {
managerAddress = _address;
}
function setPaused(bool _paused) public onlyOwner {
paused = _paused;
}
function createPositionForGivenSqrtPrices(
uint160 sqrtPriceLowerX96,
uint160 sqrtPriceUpperX96,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0OutMin,
uint256 amount1OutMin
) public payable onlyOwner isPaused {
require(_currentPositionId == 0);
// Check for token allowance
_checkAllowance(token0, amount0Desired);
_checkAllowance(token1, amount1Desired);
// Receive tokens
_transferTokenFrom(token0, msg.sender, amount0Desired);
_transferTokenFrom(token1, msg.sender, amount1Desired);
// Create position in uniswap
uint128 liquidity = _createPositionForGivenSqrtPrices(
sqrtPriceLowerX96,
sqrtPriceUpperX96,
amount0OutMin,
amount1OutMin
);
// Refund tokens from uniswap
_refundFromUniswap();
// Mint tokens to msg.sender
_mint(msg.sender, liquidity);
// Return tokens to caller
_refund(Balances(0, 0));
}
function changePositionForGivenSqrtPrices(
uint160 sqrtPriceLowerX96,
uint160 sqrtPriceUpperX96,
uint256 amount0OutMin,
uint256 amount1OutMin
) public isAllowedCaller isPaused {
require(_currentPositionId > 0);
(, , , , , , , uint128 liquidity, , , , ) = uniswapV3PositionsNFT.positions(_currentPositionId);
_removeLiquidity(liquidity);
_createPositionForGivenSqrtPrices(
sqrtPriceLowerX96,
sqrtPriceUpperX96,
amount0OutMin,
amount1OutMin
);
// Refund tokens from uniswap
_refundFromUniswap();
emit PositionChanged(msg.sender, _currentPositionId, sqrtPriceLowerX96, sqrtPriceUpperX96);
}
function addLiquidity(
uint256 amount0,
uint256 amount1,
uint256 amount0OutMin,
uint256 amount1OutMin
) public payable isPaused {
require(_currentPositionId > 0);
(uint256 amount0CurrentLiq, uint256 amount1CurrentLiq) = getCurrentAmountsForPosition();
require(
amount0CurrentLiq.add(amount0) <= maxPoolLimitInToken0 &&
amount1CurrentLiq.add(amount1) <= maxPoolLimitInToken1
);
_checkAllowance(token0, amount0);
_checkAllowance(token1, amount1);
// Collect tokens from position to the contract.
// Get balance of contract without user tokens, but with collected ones.
// Swap them in order to have a right proportion.
// Increase liquidity.
_collectFeeAndReinvest(amount0OutMin, amount1OutMin, msg.value);
// Contract balance of tokens after collecting fee and increasing liquidity (without user eth amount).
(uint256 contractAmount0, uint256 contractAmount1) = _getBalances(msg.value);
// Receive tokens from user.
_transferTokenFrom(token0, msg.sender, amount0);
_transferTokenFrom(token1, msg.sender, amount1);
(, , , , , , , uint128 prevLiquidity, , , , ) = uniswapV3PositionsNFT.positions(
_currentPositionId
);
// Add user tokens to position liquidity.
uint128 liquidity = _addUserLiquidity(
Balances(contractAmount0, contractAmount1),
amount0,
amount1
);
uint256 amount = _calculateAmountForLiquidity(prevLiquidity, liquidity);
_refundFromUniswap();
_mint(msg.sender, amount);
_refund(Balances(contractAmount0, contractAmount1));
emit LiquidityAdded(msg.sender, liquidity, amount0, amount1);
}
function collectFee(uint256 amount0OutMin, uint256 amount1OutMin)
public
isAllowedCaller
isPaused
{
_collectFeeAndReinvest(amount0OutMin, amount1OutMin, 0);
}
function _collectFee() private returns (bool) {
(uint256 amount0Collected, uint256 amount1Collected) = uniswapV3PositionsNFT.collect(
INonfungiblePositionManager.CollectParams({
tokenId: _currentPositionId,
recipient: address(this),
amount0Max: type(uint128).max,
amount1Max: type(uint128).max
})
);
if (amount0Collected > 0 || amount1Collected > 0) {
_withdraw(_isWETH(token0) ? amount0Collected : amount1Collected);
_transferManagementFee(amount0Collected, amount1Collected);
emit FeeCollected(msg.sender, amount0Collected, amount1Collected);
return true;
}
return false;
}
function _collectFeeAndReinvest(
uint256 amount0OutMin,
uint256 amount1OutMin,
uint256 userMsgValue
) private isPaused {
require(_currentPositionId > 0);
bool isCollected = _collectFee();
if (!isCollected) {
return;
}
// Contract balance of tokens after collect and before swap (without user amount of eth).
(uint256 contractAmount0, uint256 contractAmount1) = _getBalances(userMsgValue);
(, , , , , int24 tickLower, int24 tickUpper, , , , , ) = uniswapV3PositionsNFT.positions(
_currentPositionId
);
(, , bool shouldIncreaseLiquidity) = _swapTokensStrategy(
Balances(contractAmount0, contractAmount1),
Ticks(tickLower, tickUpper),
amount0OutMin,
amount1OutMin
);
if (!shouldIncreaseLiquidity) {
return;
}
// Contract balance of tokens after swap (without user amount of eth).
(contractAmount0, contractAmount1) = _getBalances(userMsgValue);
uint256 valueETH = 0;
if (_isWETH(token0) || _isWETH(token1)) {
valueETH = _isWETH(token0) ? contractAmount0 : contractAmount1;
}
_increaseAllowance(token0, address(uniswapV3PositionsNFT), contractAmount0);
_increaseAllowance(token1, address(uniswapV3PositionsNFT), contractAmount1);
uniswapV3PositionsNFT.increaseLiquidity{ value: valueETH }(
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: _currentPositionId,
amount0Desired: contractAmount0,
amount1Desired: contractAmount1,
amount0Min: _calculateAmountMin(contractAmount0),
amount1Min: _calculateAmountMin(contractAmount1),
deadline: 10000000000
})
);
// Refund tokens from uniswap.
_refundFromUniswap();
}
function claim(
uint256 amount,
uint256 amount0OutMin,
uint256 amount1OutMin
) public isPaused {
(uint256 amount0Decreased, uint256 amount1Decreased) = _claim(
amount,
amount0OutMin,
amount1OutMin
);
_transferToken(token0, msg.sender, amount0Decreased);
_transferToken(token1, msg.sender, amount1Decreased);
emit Claimed(msg.sender, amount, amount0Decreased, amount1Decreased);
}
function claimToken(
address token,
uint256 amount,
uint256 amount0OutMin,
uint256 amount1OutMin
) public isPaused {
require(token == token0 || token == token1);
(uint256 amount0WithoutFee, uint256 amount1WithoutFee) = _claim(
amount,
amount0OutMin,
amount1OutMin
);
uint256 amountForToken;
(uint256 amountOutToken, address secondToken, uint256 amountDecreased) = token == token0
? (amount0WithoutFee, token1, amount1WithoutFee)
: (amount1WithoutFee, token0, amount0WithoutFee);
if (amountDecreased > 0) {
(amountForToken) = _swapExact(secondToken, amountDecreased, 0);
}
_transferToken(token, msg.sender, amountOutToken.add(amountForToken));
emit Claimed(msg.sender, amount, amount0WithoutFee, amount1WithoutFee);
}
// Private functions
function _isWETH(address token) private pure returns (bool) {
return token == WETH;
}
function _checkAllowance(address token, uint256 amount) private view {
if (_isWETH(token)) {
require(amount <= msg.value);
return;
}
require(ERC20(token).allowance(msg.sender, address(this)) >= amount);
}
function _transferToken(
address token,
address receiver,
uint256 amount
) private {
if (_isWETH(token)) {
TransferHelper.safeTransferETH(receiver, amount);
return;
}
TransferHelper.safeTransfer(token, receiver, amount);
}
function _createPositionForGivenSqrtPrices(
uint160 sqrtPriceLowerX96,
uint160 sqrtPriceUpperX96,
uint256 amount0OutMin,
uint256 amount1OutMin
) private returns (uint128) {
int24 tickLower = getTickForSqrtPrice(sqrtPriceLowerX96);
int24 tickUpper = getTickForSqrtPrice(sqrtPriceUpperX96);
(uint256 amount0ForSwap, uint256 amount1ForSwap) = getBalances();
(uint256 amount0, uint256 amount1, ) = _swapTokensStrategy(
Balances(amount0ForSwap, amount1ForSwap),
Ticks(tickLower, tickUpper),
amount0OutMin,
amount1OutMin
);
require(tickUpper > tickLower);
_increaseAllowance(token0, address(uniswapV3PositionsNFT), amount0);
_increaseAllowance(token1, address(uniswapV3PositionsNFT), amount1);
uint256 valueETH = 0;
if (_isWETH(token0) || _isWETH(token1)) {
valueETH = _isWETH(token0) ? amount0 : amount1;
}
(uint256 tokenId, uint128 liquidity, , ) = uniswapV3PositionsNFT.mint{ value: valueETH }(
INonfungiblePositionManager.MintParams({
token0: token0,
token1: token1,
fee: protocolFee,
tickLower: tickLower,
tickUpper: tickUpper,
amount0Desired: amount0,
amount1Desired: amount1,
amount0Min: _calculateAmountMin(amount0),
amount1Min: _calculateAmountMin(amount1),
recipient: address(this),
deadline: 10000000000
})
);
_currentPositionId = tokenId;
return liquidity;
}
function _increaseAllowance(
address token,
address receiver,
uint256 amount
) private {
if (_isWETH(token)) {
return;
}
uint256 allowed = ERC20(token).allowance(address(this), receiver);
if (allowed != 0) {
ERC20(token).safeDecreaseAllowance(receiver, allowed);
}
ERC20(token).safeIncreaseAllowance(receiver, amount);
}
function _swapTokensStrategy(
Balances memory balances,
Ticks memory ticks,
uint256 amount0OutMin,
uint256 amount1OutMin
)
internal
returns (
uint256 amount0,
uint256 amount1,
bool isRebalanced
)
{
(
uint256 amount0ToSwap,
uint256 amount1ToSwap,
uint256 amount0AfterSwap,
uint256 amount1AfterSwap,
) = Exchanger(exchanger).rebalance(
ticks.tickLower,
ticks.tickUpper,
balances.amount0,
balances.amount1
);
if (amount0AfterSwap == 0 || amount1AfterSwap == 0) {
isRebalanced = false;
return (0, 0, isRebalanced);
}
isRebalanced = true;
if (amount0ToSwap != 0) {
_swapExact(token0, amount0ToSwap, amount1OutMin);
} else if (amount1ToSwap != 0) {
_swapExact(token1, amount1ToSwap, amount0OutMin);
}
(amount0, amount1) = getBalances();
}
function _getBalances(uint256 transferredAmount)
private
view
returns (uint256 amount0, uint256 amount1)
{
amount0 = _isWETH(token0)
? address(this).balance.sub(transferredAmount)
: ERC20(token0).balanceOf(address(this));
amount1 = _isWETH(token1)
? address(this).balance.sub(transferredAmount)
: ERC20(token1).balanceOf(address(this));
}
function _swapExact(
address token,
uint256 amount,
uint256 amountOutMin
) private returns (uint256 amountOut) {
return
_isWETH(token)
? _swapExactETHToTokens(amount, amountOutMin)
: _swapExactTokens(token, amount, amountOutMin);
}
function _swapExactTokens(
address tokenIn,
uint256 amountIn,
uint256 amountOutMin
) private returns (uint256 amountOut) {
_increaseAllowance(tokenIn, uniswapV3Router, amountIn);
address tokenOut = tokenIn == token0 ? token1 : token0;
(amountOut) = ISwapRouter(uniswapV3Router).exactInputSingle(
ISwapRouter.ExactInputSingleParams({
tokenIn: tokenIn,
tokenOut: tokenOut,
fee: protocolFee,
recipient: address(this),
deadline: 10000000000,
amountIn: amountIn,
amountOutMinimum: amountOutMin,
sqrtPriceLimitX96: 0
})
);
if (_isWETH(tokenOut)) {
IWETH9(tokenOut).withdraw(IWETH9(tokenOut).balanceOf(address(this)));
}
}
function _swapExactETHToTokens(uint256 amountIn, uint256 amountOutMin)
private
returns (uint256 amountOut)
{
require(_isWETH(token0) || _isWETH(token1));
(address tokenInWETH, address tokenOutNotWETH) = _isWETH(token0)
? (token0, token1)
: (token1, token0);
(amountOut) = ISwapRouter(uniswapV3Router).exactInputSingle{ value: amountIn }(
ISwapRouter.ExactInputSingleParams({
tokenIn: tokenInWETH,
tokenOut: tokenOutNotWETH,
fee: protocolFee,
recipient: address(this),
deadline: 10000000000,
amountIn: amountIn,
amountOutMinimum: amountOutMin,
sqrtPriceLimitX96: 0
})
);
}
function _refund(Balances memory startBalances) private {
(uint256 amount0, uint256 amount1) = getBalances();
_refundETHOrToken(amount0, startBalances.amount0, token0);
_refundETHOrToken(amount1, startBalances.amount1, token1);
}
function _refundETHOrToken(
uint256 balance,
uint256 startBalance,
address token
) private {
if (balance > startBalance) {
_isWETH(token)
? TransferHelper.safeTransferETH(msg.sender, balance - startBalance)
: TransferHelper.safeTransfer(token, msg.sender, balance - startBalance);
}
}
function _removeLiquidity(uint128 liquidity) private returns (uint256 amount0, uint256 amount1) {
(uint256 amount0CurrentLiq, uint256 amount1CurrentLiq) = getCurrentAmountsForPosition();
(uint256 amount0Decreased, uint256 amount1Decreased) = uniswapV3PositionsNFT.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: _currentPositionId,
liquidity: liquidity,
amount0Min: _calculateAmountMin(amount0CurrentLiq),
amount1Min: _calculateAmountMin(amount1CurrentLiq),
deadline: 10000000000
})
);
(uint256 amount0Collected, uint256 amount1Collected) = uniswapV3PositionsNFT.collect(
INonfungiblePositionManager.CollectParams({
tokenId: _currentPositionId,
recipient: address(this),
amount0Max: type(uint128).max,
amount1Max: type(uint128).max
})
);
uint256 amount0Fee = amount0Collected.sub(amount0Decreased);
uint256 amount1Fee = amount1Collected.sub(amount1Decreased);
emit FeeCollected(msg.sender, amount0Fee, amount1Fee);
_withdraw(_isWETH(token0) ? amount0Collected : amount1Collected);
(uint256 amount0FeeForVault, uint256 amount1FeeForVault) = _transferManagementFee(
amount0Fee,
amount1Fee
);
emit LiquidityRemoved(msg.sender, liquidity, amount0Collected, amount1Collected);
return (amount0Collected.sub(amount0FeeForVault), amount1Collected.sub(amount1FeeForVault));
}
function _withdraw(uint256 amount) private {
if (!(_isWETH(token0) || _isWETH(token1))) {
return;
}
IWETH9(WETH).withdraw(amount);
}
function _addUserLiquidity(
Balances memory contractBalance,
uint256 amount0,
uint256 amount1
) private returns (uint128 liquidity) {
(, , , , , int24 tickLower, int24 tickUpper, , , , , ) = uniswapV3PositionsNFT.positions(
_currentPositionId
);
(uint256 contractAmount0AfterSwap, uint256 contractAmount1AfterSwap, ) = _swapTokensStrategy(
Balances(amount0, amount1),
Ticks(tickLower, tickUpper),
0,
0
);
uint256 userAmount0 = contractAmount0AfterSwap.sub(contractBalance.amount0);
uint256 userAmount1 = contractAmount1AfterSwap.sub(contractBalance.amount1);
uint256 valueETH = 0;
if (_isWETH(token0) || _isWETH(token1)) {
valueETH = _isWETH(token0) ? userAmount0 : userAmount1;
}
_increaseAllowance(token0, address(uniswapV3PositionsNFT), userAmount0);
_increaseAllowance(token1, address(uniswapV3PositionsNFT), userAmount1);
(liquidity, , ) = uniswapV3PositionsNFT.increaseLiquidity{ value: valueETH }(
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: _currentPositionId,
amount0Desired: userAmount0,
amount1Desired: userAmount1,
amount0Min: _calculateAmountMin(userAmount0),
amount1Min: _calculateAmountMin(userAmount1),
deadline: 10000000000
})
);
}
function _transferManagementFee(uint256 amount0, uint256 amount1)
private
returns (uint256 amount0FeeForVault, uint256 amount1FeeForVault)
{
amount0FeeForVault = 0;
amount1FeeForVault = 0;
if (amount0 > 0) {
amount0FeeForVault = FullMath.mulDiv(amount0, currentManagementFeePercent, hundredPercent);
_transferToken(token0, vaultAddress, amount0FeeForVault);
}
if (amount1 > 0) {
amount1FeeForVault = FullMath.mulDiv(amount1, currentManagementFeePercent, hundredPercent);
_transferToken(token1, vaultAddress, amount1FeeForVault);
}
}
function _transferTokenFrom(
address token,
address sender,
uint256 amount
) private {
if (_isWETH(token)) {
return;
}
ERC20(token).safeTransferFrom(sender, address(this), amount);
}
function _claim(
uint256 amount,
uint256 amount0OutMin,
uint256 amount1OutMin
) private returns (uint256 amount0Decreased, uint256 amount1Decreased) {
require(_currentPositionId > 0);
require(amount <= balanceOf(msg.sender));
(, , , , , , , uint128 newLiquidity, , , , ) = uniswapV3PositionsNFT.positions(
_currentPositionId
);
uint128 shareForLiquidity = _toUint128(
FullMath.mulDiv(uint256(newLiquidity), amount, totalSupply())
);
_burn(msg.sender, amount);
(amount0Decreased, amount1Decreased) = uniswapV3PositionsNFT.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: _currentPositionId,
liquidity: shareForLiquidity,
amount0Min: amount0OutMin,
amount1Min: amount1OutMin,
deadline: 10000000000
})
);
(uint256 amount0Collected, uint256 amount1Collected) = uniswapV3PositionsNFT.collect(
INonfungiblePositionManager.CollectParams({
tokenId: _currentPositionId,
recipient: address(this),
amount0Max: _toUint128(amount0Decreased),
amount1Max: _toUint128(amount1Decreased)
})
);
_withdraw(_isWETH(token0) ? amount0Collected : amount1Collected);
uint256 amount0feeVault = FullMath.mulDiv(amount0Collected, currentVaultFee, hundredPercent);
uint256 amount1feeVault = FullMath.mulDiv(amount1Collected, currentVaultFee, hundredPercent);
uint256 amount0Claimed = amount0Collected.sub(amount0feeVault);
uint256 amount1Claimed = amount1Collected.sub(amount1feeVault);
_transferToken(token0, vaultAddress, amount0feeVault);
_transferToken(token1, vaultAddress, amount1feeVault);
return (amount0Claimed, amount1Claimed);
}
function _calculateAmountForLiquidity(uint128 prevLiquidity, uint128 newLiquidity)
private
view
returns (uint256 amount)
{
if (prevLiquidity == 0) {
amount = newLiquidity;
} else {
amount = FullMath.mulDiv(totalSupply(), uint256(newLiquidity), uint256(prevLiquidity));
}
}
function _toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
function _refundFromUniswap() private {
// Refund tokens from uniswap
if (_isWETH(token0)) {
uniswapV3PositionsNFT.refundETH();
uniswapV3PositionsNFT.unwrapWETH9(0, address(this));
} else {
uniswapV3PositionsNFT.sweepToken(token0, 0, address(this));
}
// Refund tokens from uniswap
if (_isWETH(token1)) {
uniswapV3PositionsNFT.refundETH();
uniswapV3PositionsNFT.unwrapWETH9(0, address(this));
} else {
uniswapV3PositionsNFT.sweepToken(token1, 0, address(this));
}
}
function _calculateAmountMin(uint256 amount) private view returns (uint256 amountMin) {
amountMin = FullMath.mulDiv(amount, percentOfAmountMin, hundredPercent);
}
}
// 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.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev Errors with 'SA' if transfer fails
/// @param token The contract address of the token to be approved
/// @param to The target of the approval
/// @param value The amount of the given token the target will be allowed to spend
function safeApprove(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
// 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: GPL-2.0-or-later
pragma solidity =0.7.6;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
/// @title Interface for WETH9
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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_) {
_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.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;
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: Unlicense
pragma solidity >=0.7.6;
pragma abicoder v2;
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-core/contracts/libraries/LiquidityMath.sol';
import '@uniswap/v3-core/contracts/libraries/SqrtPriceMath.sol';
import '@uniswap/v3-core/contracts/libraries/SwapMath.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint128.sol';
import '@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol';
import './libraries/TickBitmap.sol';
contract Exchanger {
using TickBitmap for IUniswapV3Pool;
using SafeCast for uint256;
using SafeCast for uint128;
struct Slot0 {
// the current price
uint160 sqrtPriceX96;
// the current tick
int24 tick;
// the current protocol fee as a percentage of the swap fee taken on withdrawal
// represented as an integer denominator (1/x)%
uint8 feeProtocol;
}
struct SwapCache {
// the protocol fee for the input token
uint8 feeProtocol;
// lowerPrice
uint160 sqrtRatioAX96;
// upperPrice
uint160 sqrtRatioBX96;
// amount0 = token0
uint256 amount0;
// amount1 = token1
uint256 amount1;
bool originalZeroForOne;
}
// the top level state of the swap, the results of which are recorded in storage at the end
struct SwapState {
// the amount remaining to be swapped in/out of the input/output asset
uint256 amountSpecifiedRemaining;
uint256 sellAmount0;
uint256 sellAmount1;
uint256 amount0AfterSwap;
uint256 amount1AfterSwap;
// current sqrt(price)
uint160 sqrtPriceX96;
// the tick associated with the current price
int24 tick;
// the current liquidity in range
uint128 liquidity;
bool zeroForOneAfterSwap;
}
struct StepComputations {
// the price at the beginning of the step
uint160 sqrtPriceStartX96;
// the next tick to swap to from the current tick in the swap direction
int24 tickNext;
// whether tickNext is initialized or not
bool initialized;
// sqrt(price) for the next tick (1/0)
uint160 sqrtPriceNextX96;
// how much is being swapped in in this step
uint256 amountIn;
// how much is being swapped out
uint256 amountOut;
// how much fee is being paid in
uint256 feeAmount;
}
uint256 private constant EPSILON = 10**8;
int24 public immutable tickSpacing;
uint24 public immutable protocolFee;
IUniswapV3Pool public immutable uniswapV3Pool;
address public immutable token0;
address public immutable token1;
constructor(address _uniswapV3Pool) {
uniswapV3Pool = IUniswapV3Pool(_uniswapV3Pool);
{
IUniswapV3Pool UniswapV3Pool = IUniswapV3Pool(_uniswapV3Pool);
token0 = UniswapV3Pool.token0();
token1 = UniswapV3Pool.token1();
protocolFee = UniswapV3Pool.fee();
tickSpacing = UniswapV3Pool.tickSpacing();
}
}
function _bestAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) private pure returns (uint256, uint256) {
require(sqrtRatioAX96 <= sqrtRatioX96, 'The current price lower than expected');
require(sqrtRatioX96 <= sqrtRatioBX96, 'The current price upper than expected');
uint128 liquidity0 = LiquidityAmounts.getLiquidityForAmount0(
sqrtRatioX96,
sqrtRatioBX96,
amount0
);
uint128 liquidity1 = LiquidityAmounts.getLiquidityForAmount1(
sqrtRatioAX96,
sqrtRatioX96,
amount1
);
uint256 midLiquidity = ((uint256(liquidity0) + uint256(liquidity1)) >> 1);
return (
uint256(SqrtPriceMath.getAmount0Delta(sqrtRatioX96, sqrtRatioBX96, int128(midLiquidity))),
uint256(SqrtPriceMath.getAmount1Delta(sqrtRatioAX96, sqrtRatioX96, int128(midLiquidity)))
);
}
function _zeroForOne(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
)
private
pure
returns (
bool,
uint256,
bool
)
{
(uint256 bestAmount0, uint256 bestAmount1) = _bestAmounts(
sqrtRatioX96,
sqrtRatioAX96,
sqrtRatioBX96,
amount0,
amount1
);
if (bestAmount1 < amount1) {
// we need sell token1
return (false, amount1 - bestAmount1, false);
}
if (amount0 >= bestAmount0) {
// we need sell token0
return (true, amount0 - bestAmount0, false);
}
// overflow
return (true, 0, true);
}
function rebalance(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
)
public
view
returns (
uint256,
uint256,
uint256,
uint256,
uint160
)
{
Slot0 memory slot0Start;
{
(uint160 sqrtPriceX96, int24 tick, , , , uint8 feeProtocol, ) = uniswapV3Pool.slot0();
slot0Start = Slot0({ sqrtPriceX96: sqrtPriceX96, tick: tick, feeProtocol: feeProtocol });
}
SwapCache memory cache = SwapCache({
feeProtocol: 0,
sqrtRatioAX96: TickMath.getSqrtRatioAtTick(tickLower),
sqrtRatioBX96: TickMath.getSqrtRatioAtTick(tickUpper),
amount0: amount0,
amount1: amount1,
originalZeroForOne: false
});
SwapState memory state = SwapState({
amountSpecifiedRemaining: 0,
sellAmount0: 0,
sellAmount1: 0,
amount0AfterSwap: 0,
amount1AfterSwap: 0,
sqrtPriceX96: slot0Start.sqrtPriceX96,
tick: slot0Start.tick,
liquidity: uniswapV3Pool.liquidity(),
zeroForOneAfterSwap: false
});
bool overflow;
(cache.originalZeroForOne, state.amountSpecifiedRemaining, overflow) = _zeroForOne(
slot0Start.sqrtPriceX96,
cache.sqrtRatioAX96,
cache.sqrtRatioBX96,
cache.amount0,
cache.amount1
);
if (overflow) {
return (0, 0, 0, 0, 0);
}
cache.feeProtocol = cache.originalZeroForOne
? (slot0Start.feeProtocol % 16)
: (slot0Start.feeProtocol >> 4);
while (state.amountSpecifiedRemaining > 0) {
StepComputations memory step;
step.sqrtPriceStartX96 = state.sqrtPriceX96;
(step.tickNext, step.initialized) = uniswapV3Pool.nextInitializedTickWithinOneWord(
state.tick,
tickSpacing,
cache.originalZeroForOne
);
// ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds
if (step.tickNext < TickMath.MIN_TICK) {
step.tickNext = TickMath.MIN_TICK;
} else if (step.tickNext > TickMath.MAX_TICK) {
step.tickNext = TickMath.MAX_TICK;
}
// get the price for the next tick
step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);
uint160 sqrtPriceX96BeforeSwap = state.sqrtPriceX96;
uint160 sqrtRatioTargetX96;
{
uint160 sqrtPriceLimitX96 = cache.originalZeroForOne
? TickMath.MIN_SQRT_RATIO + 1
: TickMath.MAX_SQRT_RATIO - 1;
sqrtRatioTargetX96 = (
cache.originalZeroForOne
? step.sqrtPriceNextX96 < sqrtPriceLimitX96
: step.sqrtPriceNextX96 > sqrtPriceLimitX96
)
? sqrtPriceLimitX96
: step.sqrtPriceNextX96;
}
// compute values to swap to the target tick, price limit, or point where input/output amount is exhausted
(state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath
.computeSwapStep(
sqrtPriceX96BeforeSwap,
sqrtRatioTargetX96,
state.liquidity,
state.amountSpecifiedRemaining.toInt256(),
protocolFee
);
if (cache.originalZeroForOne) {
state.amount0AfterSwap = cache.amount0 - (step.amountIn + step.feeAmount);
state.amount1AfterSwap = cache.amount1 + (step.amountOut);
} else {
state.amount0AfterSwap = cache.amount0 + (step.amountOut);
state.amount1AfterSwap = cache.amount1 - (step.amountIn + step.feeAmount);
}
uint256 previousAmountRemaining = state.amountSpecifiedRemaining;
(state.zeroForOneAfterSwap, state.amountSpecifiedRemaining, overflow) = _zeroForOne(
state.sqrtPriceX96,
cache.sqrtRatioAX96,
cache.sqrtRatioBX96,
state.amount0AfterSwap,
state.amount1AfterSwap
);
if (overflow) {
return (0, 0, 0, 0, 0);
}
// We swapped too much, which means that we need to swap in the backward direction
// But we don't want to swap in the backward direction, we need to swap less in forward direction
// Let's recalculate forward swap again
// Or, if we swapped the full amount
if (
state.zeroForOneAfterSwap != cache.originalZeroForOne ||
state.amountSpecifiedRemaining < EPSILON
) {
// let's do binary search to find right value which we need pass into swap
int256 l = 0;
int256 r = 2 * previousAmountRemaining.toInt256();
uint256 i = 0;
while (true) {
i = i + 1;
int256 mid = (l + r) / 2;
(state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath
.computeSwapStep(
sqrtPriceX96BeforeSwap,
sqrtRatioTargetX96,
state.liquidity,
mid,
protocolFee
);
if (cache.originalZeroForOne) {
state.amount0AfterSwap = cache.amount0 - (step.amountIn + step.feeAmount);
state.amount1AfterSwap = cache.amount1 + (step.amountOut);
} else {
state.amount0AfterSwap = cache.amount0 + (step.amountOut);
state.amount1AfterSwap = cache.amount1 - (step.amountIn + step.feeAmount);
}
uint128 liquidity0 = LiquidityAmounts.getLiquidityForAmount0(
state.sqrtPriceX96,
cache.sqrtRatioBX96,
state.amount0AfterSwap
);
uint128 liquidity1 = LiquidityAmounts.getLiquidityForAmount1(
cache.sqrtRatioAX96,
state.sqrtPriceX96,
state.amount1AfterSwap
);
bool rightDirection = false;
if (cache.originalZeroForOne) {
if (liquidity0 > liquidity1) {
rightDirection = true;
l = mid;
} else {
r = mid;
}
} else {
if (liquidity0 < liquidity1) {
rightDirection = true;
l = mid;
} else {
r = mid;
}
}
if (rightDirection && (i >= 70 || l + 1 >= r)) {
if (cache.originalZeroForOne) {
state.sellAmount0 += step.amountIn + step.feeAmount;
} else {
state.sellAmount1 += step.amountIn + step.feeAmount;
}
break;
}
}
state.amountSpecifiedRemaining = 0;
} else {
if (cache.originalZeroForOne) {
state.sellAmount0 += step.amountIn + step.feeAmount;
} else {
state.sellAmount1 += step.amountIn + step.feeAmount;
}
cache.amount0 = state.amount0AfterSwap;
cache.amount1 = state.amount1AfterSwap;
// if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee
if (cache.feeProtocol > 0) {
uint256 delta = step.feeAmount / cache.feeProtocol;
step.feeAmount -= delta;
}
// shift tick if we reached the next price
if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {
// if the tick is initialized, run the tick transition
if (step.initialized) {
(, int128 liquidityNet, , , , , , ) = uniswapV3Pool.ticks(step.tickNext);
// if we're moving leftward, we interpret liquidityNet as the opposite sign
// safe because liquidityNet cannot be type(int128).min
if (cache.originalZeroForOne) liquidityNet = -liquidityNet;
state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
}
state.tick = cache.originalZeroForOne ? step.tickNext - 1 : step.tickNext;
} else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {
// recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
}
}
}
return (
state.sellAmount0,
state.sellAmount1,
state.amount0AfterSwap,
state.amount1AfterSwap,
state.sqrtPriceX96
);
}
}
// 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: MIT
pragma solidity ^0.7.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.7.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: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../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.7.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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// 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: 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;
}
// 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.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 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 Math library for liquidity
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
if (y < 0) {
require((z = x - uint128(-y)) < x, 'LS');
} else {
require((z = x + uint128(y)) >= x, 'LA');
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;
import './LowGasSafeMath.sol';
import './SafeCast.sol';
import './FullMath.sol';
import './UnsafeMath.sol';
import './FixedPoint96.sol';
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
using LowGasSafeMath for uint256;
using SafeCast for uint256;
/// @notice Gets the next sqrt price given a delta of token0
/// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
/// price less in order to not send too much output.
/// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
/// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
/// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token0 to add or remove from virtual reserves
/// @param add Whether to add or remove the amount of token0
/// @return The price after adding or removing amount, depending on add
function getNextSqrtPriceFromAmount0RoundingUp(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160) {
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96;
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
if (add) {
uint256 product;
if ((product = amount * sqrtPX96) / amount == sqrtPX96) {
uint256 denominator = numerator1 + product;
if (denominator >= numerator1)
// always fits in 160 bits
return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
}
return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));
} else {
uint256 product;
// if the product overflows, we know the denominator underflows
// in addition, we must check that the denominator does not underflow
require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);
uint256 denominator = numerator1 - product;
return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
}
}
/// @notice Gets the next sqrt price given a delta of token1
/// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
/// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
/// price less in order to not send too much output.
/// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
/// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta
/// @param liquidity The amount of usable liquidity
/// @param amount How much of token1 to add, or remove, from virtual reserves
/// @param add Whether to add, or remove, the amount of token1
/// @return The price after adding or removing `amount`
function getNextSqrtPriceFromAmount1RoundingDown(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160) {
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (add) {
uint256 quotient =
(
amount <= type(uint160).max
? (amount << FixedPoint96.RESOLUTION) / liquidity
: FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
);
return uint256(sqrtPX96).add(quotient).toUint160();
} else {
uint256 quotient =
(
amount <= type(uint160).max
? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
: FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
);
require(sqrtPX96 > quotient);
// always fits 160 bits
return uint160(sqrtPX96 - quotient);
}
}
/// @notice Gets the next sqrt price given an input amount of token0 or token1
/// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
/// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
/// @param liquidity The amount of usable liquidity
/// @param amountIn How much of token0, or token1, is being swapped in
/// @param zeroForOne Whether the amount in is token0 or token1
/// @return sqrtQX96 The price after adding the input amount to token0 or token1
function getNextSqrtPriceFromInput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountIn,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96) {
require(sqrtPX96 > 0);
require(liquidity > 0);
// round to make sure that we don't pass the target price
return
zeroForOne
? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
: getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
}
/// @notice Gets the next sqrt price given an output amount of token0 or token1
/// @dev Throws if price or liquidity are 0 or the next price is out of bounds
/// @param sqrtPX96 The starting price before accounting for the output amount
/// @param liquidity The amount of usable liquidity
/// @param amountOut How much of token0, or token1, is being swapped out
/// @param zeroForOne Whether the amount out is token0 or token1
/// @return sqrtQX96 The price after removing the output amount of token0 or token1
function getNextSqrtPriceFromOutput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountOut,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96) {
require(sqrtPX96 > 0);
require(liquidity > 0);
// round to make sure that we pass the target price
return
zeroForOne
? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
: getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
}
/// @notice Gets the amount0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;
require(sqrtRatioAX96 > 0);
return
roundUp
? UnsafeMath.divRoundingUp(
FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
sqrtRatioAX96
)
: FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
}
/// @notice Gets the amount1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
roundUp
? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
: FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Helper that gets signed token0 delta
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount0 delta
/// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount0) {
return
liquidity < 0
? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
: getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
}
/// @notice Helper that gets signed token1 delta
/// @param sqrtRatioAX96 A sqrt price
/// @param sqrtRatioBX96 Another sqrt price
/// @param liquidity The change in liquidity for which to compute the amount1 delta
/// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount1) {
return
liquidity < 0
? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
: getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;
import './FullMath.sol';
import './SqrtPriceMath.sol';
/// @title Computes the result of a swap within ticks
/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
library SwapMath {
/// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
/// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
/// @param sqrtRatioCurrentX96 The current sqrt price of the pool
/// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
/// @param liquidity The usable liquidity
/// @param amountRemaining How much input or output amount is remaining to be swapped in/out
/// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
/// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target
/// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
/// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
/// @return feeAmount The amount of input that will be taken as a fee
function computeSwapStep(
uint160 sqrtRatioCurrentX96,
uint160 sqrtRatioTargetX96,
uint128 liquidity,
int256 amountRemaining,
uint24 feePips
)
internal
pure
returns (
uint160 sqrtRatioNextX96,
uint256 amountIn,
uint256 amountOut,
uint256 feeAmount
)
{
bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;
bool exactIn = amountRemaining >= 0;
if (exactIn) {
uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);
amountIn = zeroForOne
? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)
: SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;
else
sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
sqrtRatioCurrentX96,
liquidity,
amountRemainingLessFee,
zeroForOne
);
} else {
amountOut = zeroForOne
? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)
: SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;
else
sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(
sqrtRatioCurrentX96,
liquidity,
uint256(-amountRemaining),
zeroForOne
);
}
bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;
// get the input/output amounts
if (zeroForOne) {
amountIn = max && exactIn
? amountIn
: SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);
amountOut = max && !exactIn
? amountOut
: SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);
} else {
amountIn = max && exactIn
? amountIn
: SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);
amountOut = max && !exactIn
? amountOut
: SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);
}
// cap the output amount to not exceed the remaining output amount
if (!exactIn && amountOut > uint256(-amountRemaining)) {
amountOut = uint256(-amountRemaining);
}
if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {
// we didn't reach the target, so take the remainder of the maximum input as fee
feeAmount = uint256(amountRemaining) - amountIn;
} else {
feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.5.0;
import './BitMath.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
/// @title Packed tick initialized state library
/// @notice Stores a packed mapping of tick index to its initialized state
/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
library TickBitmap {
/// @notice Computes the position in the mapping where the initialized bit for a tick lives
/// @param tick The tick for which to compute the position
/// @return wordPos The key in the mapping containing the word in which the bit is stored
/// @return bitPos The bit position in the word where the flag is stored
function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {
wordPos = int16(tick >> 8);
bitPos = uint8(tick % 256);
}
/// @notice Flips the initialized state for a given tick from false to true, or vice versa
/// @param self The mapping in which to flip the tick
/// @param tick The tick to flip
/// @param tickSpacing The spacing between usable ticks
function flipTick(
mapping(int16 => uint256) storage self,
int24 tick,
int24 tickSpacing
) internal {
require(tick % tickSpacing == 0); // ensure that the tick is spaced
(int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);
uint256 mask = 1 << bitPos;
self[wordPos] ^= mask;
}
/// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
/// to the left (less than or equal to) or right (greater than) of the given tick
/// @param self The mapping in which to compute the next initialized tick
/// @param tick The starting tick
/// @param tickSpacing The spacing between usable ticks
/// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
/// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
/// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
function nextInitializedTickWithinOneWord(
IUniswapV3Pool self,
int24 tick,
int24 tickSpacing,
bool lte
) internal view returns (int24 next, bool initialized) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity
if (lte) {
(int16 wordPos, uint8 bitPos) = position(compressed);
// all the 1s at or to the right of the current bitPos
uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);
uint256 masked = self.tickBitmap(wordPos) & mask;
// if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
initialized = masked != 0;
// overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
next = initialized
? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing
: (compressed - int24(bitPos)) * tickSpacing;
} else {
// start from the word of the next tick, since the current tick state doesn't matter
(int16 wordPos, uint8 bitPos) = position(compressed + 1);
// all the 1s at or to the left of the bitPos
uint256 mask = ~((1 << bitPos) - 1);
uint256 masked = self.tickBitmap(wordPos) & mask;
// if there are no initialized ticks to the left of the current tick, return leftmost in the word
initialized = masked != 0;
// overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
next = initialized
? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing
: (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.0;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
/// @notice Returns ceil(x / y)
/// @dev division by 0 has unspecified behavior, and must be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @dev The function satisfies the property:
/// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @dev The function satisfies the property:
/// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
r = 255;
if (x & type(uint128).max > 0) {
r -= 128;
} else {
x >>= 128;
}
if (x & type(uint64).max > 0) {
r -= 64;
} else {
x >>= 64;
}
if (x & type(uint32).max > 0) {
r -= 32;
} else {
x >>= 32;
}
if (x & type(uint16).max > 0) {
r -= 16;
} else {
x >>= 16;
}
if (x & type(uint8).max > 0) {
r -= 8;
} else {
x >>= 8;
}
if (x & 0xf > 0) {
r -= 4;
} else {
x >>= 4;
}
if (x & 0x3 > 0) {
r -= 2;
} else {
x >>= 2;
}
if (x & 0x1 > 0) r -= 1;
}
} | Refund tokens from uniswap Refund tokens from uniswap | function _refundFromUniswap() private {
if (_isWETH(token0)) {
uniswapV3PositionsNFT.refundETH();
uniswapV3PositionsNFT.unwrapWETH9(0, address(this));
uniswapV3PositionsNFT.sweepToken(token0, 0, address(this));
}
if (_isWETH(token1)) {
uniswapV3PositionsNFT.refundETH();
uniswapV3PositionsNFT.unwrapWETH9(0, address(this));
uniswapV3PositionsNFT.sweepToken(token1, 0, address(this));
}
}
| 115,319 | [
1,
21537,
2430,
628,
640,
291,
91,
438,
3941,
1074,
2430,
628,
640,
291,
91,
438,
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,
225,
445,
389,
1734,
1074,
1265,
984,
291,
91,
438,
1435,
3238,
288,
203,
565,
309,
261,
67,
291,
59,
1584,
44,
12,
2316,
20,
3719,
288,
203,
1377,
640,
291,
91,
438,
58,
23,
11024,
50,
4464,
18,
1734,
1074,
1584,
44,
5621,
203,
1377,
640,
291,
91,
438,
58,
23,
11024,
50,
4464,
18,
318,
4113,
59,
1584,
44,
29,
12,
20,
16,
1758,
12,
2211,
10019,
203,
1377,
640,
291,
91,
438,
58,
23,
11024,
50,
4464,
18,
87,
25236,
1345,
12,
2316,
20,
16,
374,
16,
1758,
12,
2211,
10019,
203,
565,
289,
203,
203,
565,
309,
261,
67,
291,
59,
1584,
44,
12,
2316,
21,
3719,
288,
203,
1377,
640,
291,
91,
438,
58,
23,
11024,
50,
4464,
18,
1734,
1074,
1584,
44,
5621,
203,
1377,
640,
291,
91,
438,
58,
23,
11024,
50,
4464,
18,
318,
4113,
59,
1584,
44,
29,
12,
20,
16,
1758,
12,
2211,
10019,
203,
1377,
640,
291,
91,
438,
58,
23,
11024,
50,
4464,
18,
87,
25236,
1345,
12,
2316,
21,
16,
374,
16,
1758,
12,
2211,
10019,
203,
565,
289,
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
] |
./full_match/42/0x497C661fA4CBCB325342a99eA39e838f1DBFF324/sources/contracts/SideContract.sol | File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721URIStorage.sol)* @dev ERC721 token with storage based token URI management./ Optional mapping for token URIs | abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
mapping(uint256 => string) private _tokenURIs;
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.0;
{
require(
_exists(tokenId),
"ERC721URIStorage: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.0;
{
require(
_exists(tokenId),
"ERC721URIStorage: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.0;
{
require(
_exists(tokenId),
"ERC721URIStorage: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721URIStorage: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
| 9,584,972 | [
1,
812,
30,
632,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
27,
5340,
19,
9489,
19,
654,
39,
27,
5340,
3098,
3245,
18,
18281,
3502,
62,
881,
84,
292,
267,
30131,
331,
24,
18,
24,
18,
20,
261,
2316,
19,
654,
39,
27,
5340,
19,
9489,
19,
654,
39,
27,
5340,
3098,
3245,
18,
18281,
13,
225,
4232,
39,
27,
5340,
1147,
598,
2502,
2511,
1147,
3699,
11803,
18,
19,
4055,
2874,
364,
1147,
24565,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
17801,
6835,
4232,
39,
27,
5340,
3098,
3245,
353,
4232,
39,
27,
5340,
288,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
533,
13,
3238,
389,
2316,
1099,
2520,
31,
203,
203,
565,
445,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
3849,
203,
3639,
1135,
261,
1080,
3778,
13,
203,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
97,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
389,
1808,
12,
2316,
548,
3631,
203,
5411,
315,
654,
39,
27,
5340,
3098,
3245,
30,
3699,
843,
364,
1661,
19041,
1147,
6,
203,
3639,
11272,
203,
203,
3639,
533,
3778,
389,
2316,
3098,
273,
389,
2316,
1099,
2520,
63,
2316,
548,
15533,
203,
3639,
533,
3778,
1026,
273,
389,
1969,
3098,
5621,
203,
203,
3639,
309,
261,
3890,
12,
1969,
2934,
2469,
422,
374,
13,
288,
203,
5411,
327,
389,
2316,
3098,
31,
203,
3639,
289,
203,
3639,
309,
261,
3890,
24899,
2316,
3098,
2934,
2469,
405,
374,
13,
288,
203,
5411,
327,
533,
12,
21457,
18,
3015,
4420,
329,
12,
1969,
16,
389,
2316,
3098,
10019,
203,
3639,
289,
203,
203,
3639,
327,
2240,
18,
2316,
3098,
12,
2316,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
5771,
1345,
5912,
2
] |
./full_match/1/0xec3567ae258639a0FF5A02F7eAF4E4aE4416C5fe/sources/contracts/0.4.24/nos/NodeOperatorsRegistry.sol | * @notice Returns total number of node operators/ | function getNodeOperatorsCount() public view returns (uint256) {
return TOTAL_OPERATORS_COUNT_POSITION.getStorageUint256();
}
| 17,070,872 | [
1,
1356,
2078,
1300,
434,
756,
12213,
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,
5973,
24473,
1380,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
399,
19851,
67,
26110,
55,
67,
7240,
67,
15258,
18,
588,
3245,
5487,
5034,
5621,
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
] |
./partial_match/1/0x6e1781678ffE6CDc109fd3bC0833c47BD0F23de1/sources/contracts/libraries/Constants.sol | * @notice An address that identifies that current submission round is a public round./ | address internal constant VALIDATOR_PUBLIC_ROUND_ADDRESS = address(type(uint160).max);
| 16,157,894 | [
1,
979,
1758,
716,
25283,
716,
783,
8515,
3643,
353,
279,
1071,
3643,
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,
565,
1758,
2713,
5381,
15093,
3575,
67,
14939,
67,
15092,
67,
15140,
273,
1758,
12,
723,
12,
11890,
16874,
2934,
1896,
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
] |
./full_match/42220/0x1905eC0769775179A9b2e042Ce0FD59E27fD407c/sources/contracts/token/bases/staking/StakedToken.sol | * @dev Internal ERC20 _transfer of the tokenized staked tokens @param from Address to transfer from @param to Address to transfer to @param amount Amount to transfer/ Sender Recipient if cooldown was set and whole balance of sender was transferred - clear cooldown | function _transfer(
address from,
address to,
uint256 amount
) internal override {
uint256 balanceOfFrom = balanceOf(from);
_updateCurrentUnclaimedRewards(from, balanceOfFrom, true);
if (from != to) {
uint256 balanceOfTo = balanceOf(to);
_updateCurrentUnclaimedRewards(to, balanceOfTo, true);
uint256 previousSenderCooldown = stakersCooldowns[from];
stakersCooldowns[to] = getNextCooldownTimestamp(
previousSenderCooldown,
amount,
to,
balanceOfTo
);
if (balanceOfFrom == amount && previousSenderCooldown != 0) {
stakersCooldowns[from] = 0;
}
}
super._transfer(from, to, amount);
}
| 16,341,067 | [
1,
3061,
4232,
39,
3462,
389,
13866,
434,
326,
26073,
384,
9477,
2430,
225,
628,
5267,
358,
7412,
628,
225,
358,
5267,
358,
7412,
358,
225,
3844,
16811,
358,
7412,
19,
15044,
23550,
309,
27367,
2378,
1703,
444,
471,
7339,
11013,
434,
5793,
1703,
906,
4193,
300,
2424,
27367,
2378,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
3849,
288,
203,
3639,
2254,
5034,
11013,
951,
1265,
273,
11013,
951,
12,
2080,
1769,
203,
3639,
389,
2725,
3935,
984,
14784,
329,
17631,
14727,
12,
2080,
16,
11013,
951,
1265,
16,
638,
1769,
203,
203,
3639,
309,
261,
2080,
480,
358,
13,
288,
203,
5411,
2254,
5034,
11013,
951,
774,
273,
11013,
951,
12,
869,
1769,
203,
5411,
389,
2725,
3935,
984,
14784,
329,
17631,
14727,
12,
869,
16,
11013,
951,
774,
16,
638,
1769,
203,
203,
5411,
2254,
5034,
2416,
12021,
39,
1371,
2378,
273,
384,
581,
414,
39,
1371,
2378,
87,
63,
2080,
15533,
203,
5411,
384,
581,
414,
39,
1371,
2378,
87,
63,
869,
65,
273,
6927,
39,
1371,
2378,
4921,
12,
203,
7734,
2416,
12021,
39,
1371,
2378,
16,
203,
7734,
3844,
16,
203,
7734,
358,
16,
203,
7734,
11013,
951,
774,
203,
5411,
11272,
203,
5411,
309,
261,
12296,
951,
1265,
422,
3844,
597,
2416,
12021,
39,
1371,
2378,
480,
374,
13,
288,
203,
7734,
384,
581,
414,
39,
1371,
2378,
87,
63,
2080,
65,
273,
374,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2240,
6315,
13866,
12,
2080,
16,
358,
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
] |
./full_match/1/0x95f808db51579f9c7AC13e0B73075DB86016d0C6/sources/contracts/UnicusNft.sol | * @dev Returns balance of the ETH held by the contract. The amount of ETH that are held of finished auctions Calling conditions: - Only the owner of the smart contract i.e Unicus platform can invoke this @return the amount of ETH held/ | function ethBalance() public onlyOwner view returns(uint256) {
return address(this).balance - _getOngoingAuctionsBalances(false);
}
| 3,154,440 | [
1,
1356,
11013,
434,
326,
512,
2455,
15770,
635,
326,
6835,
18,
1021,
3844,
434,
512,
2455,
716,
854,
15770,
434,
6708,
279,
4062,
87,
21020,
4636,
30,
300,
5098,
326,
3410,
434,
326,
13706,
6835,
277,
18,
73,
1351,
335,
407,
4072,
848,
4356,
333,
327,
326,
3844,
434,
512,
2455,
15770,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
13750,
13937,
1435,
1071,
1338,
5541,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
327,
1758,
12,
2211,
2934,
12296,
300,
389,
588,
1398,
8162,
37,
4062,
87,
38,
26488,
12,
5743,
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
] |
./full_match/4/0xC2d0Ee71f7bd1406ef07B10C77c0A35FdB4B3Ee1/sources/localhost/CleverProtocol.sol | flush the escrow account with the corresponding percentage for this cycle and update payment flag | _cleverEscrow.withdrawWithGas(address(uint160(address(this))), cycle);
| 12,488,332 | [
1,
11330,
326,
2904,
492,
2236,
598,
326,
4656,
11622,
364,
333,
8589,
471,
1089,
5184,
2982,
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,
3639,
389,
2131,
502,
6412,
492,
18,
1918,
9446,
1190,
27998,
12,
2867,
12,
11890,
16874,
12,
2867,
12,
2211,
3719,
3631,
8589,
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
] |
./partial_match/1/0x17C714Bfb6C65bB88A223d4BF9e52aD4DF862F2f/sources/ETFUSDCAndCompound.sol | Contract(Fund) Status 0: not initialized 1: initialized 2: not enough fund came in in time 3: fundStarted 4: running 5: stoppped 6: closed | uint256 public fundStatus;
| 15,475,366 | [
1,
8924,
12,
42,
1074,
13,
2685,
374,
30,
486,
6454,
404,
30,
6454,
576,
30,
486,
7304,
284,
1074,
22497,
316,
316,
813,
890,
30,
284,
1074,
9217,
1059,
30,
3549,
1381,
30,
2132,
84,
1845,
1666,
30,
4375,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
2254,
5034,
1071,
284,
1074,
1482,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.9;
import "../contracts_common/Libraries/SigUtil.sol";
import "../contracts_common/Libraries/PriceUtil.sol";
import "../Sand.sol";
import "../Asset.sol";
import "../contracts_common/Interfaces/ERC20.sol";
import "../TheSandbox712.sol";
import "../contracts_common/BaseWithStorage/MetaTransactionReceiver.sol";
import "../contracts_common/Interfaces/ERC1271.sol";
import "../contracts_common/Interfaces/ERC1271Constants.sol";
import "../contracts_common/Interfaces/ERC1654.sol";
import "../contracts_common/Interfaces/ERC1654Constants.sol";
import "../contracts_common/Libraries/SafeMathWithRequire.sol";
contract AssetSignedAuction is ERC1654Constants, ERC1271Constants, TheSandbox712, MetaTransactionReceiver {
using SafeMathWithRequire for uint256;
enum SignatureType { DIRECT, EIP1654, EIP1271 }
bytes32 constant AUCTION_TYPEHASH = keccak256(
"Auction(address from,address token,uint256 offerId,uint256 startingPrice,uint256 endingPrice,uint256 startedAt,uint256 duration,uint256 packs,bytes ids,bytes amounts)"
);
event OfferClaimed(
address indexed seller,
address indexed buyer,
uint256 indexed offerId,
uint256 amount,
uint256 pricePaid,
uint256 feePaid
);
event OfferCancelled(address indexed seller, uint256 indexed offerId);
uint256 constant MAX_UINT256 = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// Stack too deep, grouping parameters
// AuctionData:
uint256 constant AuctionData_OfferId = 0;
uint256 constant AuctionData_StartingPrice = 1;
uint256 constant AuctionData_EndingPrice = 2;
uint256 constant AuctionData_StartedAt = 3;
uint256 constant AuctionData_Duration = 4;
uint256 constant AuctionData_Packs = 5;
mapping(address => mapping(uint256 => uint256)) claimed;
Asset _asset;
uint256 _fee10000th = 0;
address payable _feeCollector;
event FeeSetup(address feeCollector, uint256 fee10000th);
constructor(Asset asset, address admin, address initialMetaTx, address payable feeCollector, uint256 fee10000th) public {
_asset = asset;
_feeCollector = feeCollector;
_fee10000th = fee10000th;
emit FeeSetup(feeCollector, fee10000th);
_admin = admin;
_setMetaTransactionProcessor(initialMetaTx, true);
init712();
}
/// @notice set fee parameters
/// @param feeCollector address receiving the fee
/// @param fee10000th fee in 10,000th
function setFee(address payable feeCollector, uint256 fee10000th) external {
require(msg.sender == _admin, "only admin can change fee");
_feeCollector = feeCollector;
_fee10000th = fee10000th;
emit FeeSetup(feeCollector, fee10000th);
}
function _verifyParameters(
address buyer,
address payable seller,
address token,
uint256 buyAmount,
uint256[] memory auctionData,
uint256[] memory ids,
uint256[] memory amounts
) internal view {
require(ids.length == amounts.length, "ids and amounts length not matching");
require(buyer == msg.sender || (token != address(0) && _metaTransactionContracts[msg.sender]), "not authorized");
uint256 amountAlreadyClaimed = claimed[seller][auctionData[AuctionData_OfferId]];
require(amountAlreadyClaimed != MAX_UINT256, "Auction cancelled");
uint256 total = amountAlreadyClaimed.add(buyAmount);
require(total >= amountAlreadyClaimed, "overflow");
require(total <= auctionData[AuctionData_Packs], "Buy amount exceeds sell amount");
require(
auctionData[AuctionData_StartedAt] <= block.timestamp,
"Auction didn't start yet"
);
require(
auctionData[AuctionData_StartedAt].add(auctionData[AuctionData_Duration]) > block.timestamp,
"Auction finished"
);
}
/// @notice claim offer using EIP712
/// @param buyer address paying for the offer
/// @param seller address of the seller
/// @param token token used for payment
/// @param purchase buyAmount, maxTokenAmount
/// @param auctionData offerId, startingPrice, endingPrice, startedAt, duration, packs
/// @param ids ids of the Assets being sold
/// @param amounts amounts of Assets per pack
/// @param signature signature of seller
function claimSellerOffer(
address buyer,
address payable seller,
address token,
uint256[] calldata purchase, // buyAmount, maxTokenAmount
uint256[] calldata auctionData,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata signature
) external payable {
_verifyParameters(
buyer,
seller,
token,
purchase[0],
auctionData,
ids,
amounts
);
_ensureCorrectSigner(seller, token, auctionData, ids, amounts, signature, SignatureType.DIRECT, true);
_executeDeal(
token,
purchase,
buyer,
seller,
auctionData,
ids,
amounts
);
}
/// @notice claim offer using EIP712 and EIP1271 signature verification scheme
/// @param buyer address paying for the offer
/// @param seller address of the seller
/// @param token token used for payment
/// @param purchase buyAmount, maxTokenAmount
/// @param auctionData offerId, startingPrice, endingPrice, startedAt, duration, packs
/// @param ids ids of the Assets being sold
/// @param amounts amounts of Assets per pack
/// @param signature signature of seller
function claimSellerOfferViaEIP1271(
address buyer,
address payable seller,
address token,
uint256[] calldata purchase, // buyAmount, maxTokenAmount
uint256[] calldata auctionData,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata signature
) external payable {
_verifyParameters(
buyer,
seller,
token,
purchase[0],
auctionData,
ids,
amounts
);
_ensureCorrectSigner(seller, token, auctionData, ids, amounts, signature, SignatureType.EIP1271, true);
_executeDeal(
token,
purchase,
buyer,
seller,
auctionData,
ids,
amounts
);
}
/// @notice claim offer using EIP712 and EIP1654 signature verification scheme
/// @param buyer address paying for the offer
/// @param seller address of the seller
/// @param token token used for payment
/// @param purchase buyAmount, maxTokenAmount
/// @param auctionData offerId, startingPrice, endingPrice, startedAt, duration, packs
/// @param ids ids of the Assets being sold
/// @param amounts amounts of Assets per pack
/// @param signature signature of seller
function claimSellerOfferViaEIP1654(
address buyer,
address payable seller,
address token,
uint256[] calldata purchase, // buyAmount, maxTokenAmount
uint256[] calldata auctionData,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata signature
) external payable {
_verifyParameters(
buyer,
seller,
token,
purchase[0],
auctionData,
ids,
amounts
);
_ensureCorrectSigner(seller, token, auctionData, ids, amounts, signature, SignatureType.EIP1654, true);
_executeDeal(
token,
purchase,
buyer,
seller,
auctionData,
ids,
amounts
);
}
/// @notice claim offer using Basic Signature
/// @param buyer address paying for the offer
/// @param seller address of the seller
/// @param token token used for payment
/// @param purchase buyAmount, maxTokenAmount
/// @param auctionData offerId, startingPrice, endingPrice, startedAt, duration, packs
/// @param ids ids of the Assets being sold
/// @param amounts amounts of Assets per pack
/// @param signature signature of seller
function claimSellerOfferUsingBasicSig(
address buyer,
address payable seller,
address token,
uint256[] calldata purchase, // buyAmount, maxTokenAmount
uint256[] calldata auctionData,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata signature
) external payable {
_verifyParameters(
buyer,
seller,
token,
purchase[0],
auctionData,
ids,
amounts
);
_ensureCorrectSigner(seller, token, auctionData, ids, amounts, signature, SignatureType.DIRECT, false);
_executeDeal(
token,
purchase,
buyer,
seller,
auctionData,
ids,
amounts
);
}
/// @notice claim offer using Basic Signature and EIP1271 signature verification scheme
/// @param buyer address paying for the offer
/// @param seller address of the seller
/// @param token token used for payment
/// @param purchase buyAmount, maxTokenAmount
/// @param auctionData offerId, startingPrice, endingPrice, startedAt, duration, packs
/// @param ids ids of the Assets being sold
/// @param amounts amounts of Assets per pack
/// @param signature signature of seller
function claimSellerOfferUsingBasicSigViaEIP1271(
address buyer,
address payable seller,
address token,
uint256[] calldata purchase, // buyAmount, maxTokenAmount
uint256[] calldata auctionData,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata signature
) external payable {
_verifyParameters(
buyer,
seller,
token,
purchase[0],
auctionData,
ids,
amounts
);
_ensureCorrectSigner(seller, token, auctionData, ids, amounts, signature, SignatureType.EIP1271, false);
_executeDeal(
token,
purchase,
buyer,
seller,
auctionData,
ids,
amounts
);
}
/// @notice claim offer using Basic Signature and EIP1654 signature verification scheme
/// @param buyer address paying for the offer
/// @param seller address of the seller
/// @param token token used for payment
/// @param purchase buyAmount, maxTokenAmount
/// @param auctionData offerId, startingPrice, endingPrice, startedAt, duration, packs
/// @param ids ids of the Assets being sold
/// @param amounts amounts of Assets per pack
/// @param signature signature of seller
function claimSellerOfferUsingBasicSigViaEIP1654(
address buyer,
address payable seller,
address token,
uint256[] calldata purchase, // buyAmount, maxTokenAmount
uint256[] calldata auctionData,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata signature
) external payable {
_verifyParameters(
buyer,
seller,
token,
purchase[0],
auctionData,
ids,
amounts
);
_ensureCorrectSigner(seller, token, auctionData, ids, amounts, signature, SignatureType.EIP1654, false);
_executeDeal(
token,
purchase,
buyer,
seller,
auctionData,
ids,
amounts
);
}
function _executeDeal(
address token,
uint256[] memory purchase,
address buyer,
address payable seller,
uint256[] memory auctionData,
uint256[] memory ids,
uint256[] memory amounts
) internal {
uint256 offer = PriceUtil.calculateCurrentPrice(
auctionData[AuctionData_StartingPrice],
auctionData[AuctionData_EndingPrice],
auctionData[AuctionData_Duration],
block.timestamp.sub(auctionData[AuctionData_StartedAt])
).mul(purchase[0]);
claimed[seller][auctionData[AuctionData_OfferId]] = claimed[seller][auctionData[AuctionData_OfferId]].add(purchase[0]);
uint256 fee = 0;
if(_fee10000th > 0) {
fee = PriceUtil.calculateFee(offer, _fee10000th);
}
uint256 total = offer.add(fee);
require(total <= purchase[1], "offer exceeds max amount to spend");
if (token != address(0)) {
require(ERC20(token).transferFrom(buyer, seller, offer), "failed to transfer token price");
if(fee > 0) {
require(ERC20(token).transferFrom(buyer, _feeCollector, fee), "failed to collect fee");
}
} else {
require(msg.value >= total, "ETH < offer+fee");
if(msg.value > total) {
msg.sender.transfer(msg.value.sub(total));
}
seller.transfer(offer);
if(fee > 0) {
_feeCollector.transfer(fee);
}
}
uint256[] memory packAmounts = new uint256[](amounts.length);
for (uint256 i = 0; i < packAmounts.length; i++) {
packAmounts[i] = amounts[i].mul(purchase[0]);
}
_asset.safeBatchTransferFrom(seller, buyer, ids, packAmounts, "");
emit OfferClaimed(
seller,
buyer,
auctionData[AuctionData_OfferId],
purchase[0],
offer,
fee
);
}
/// @notice cancel a offer previously signed, new offer need to use a id not used yet
/// @param offerId offer to cancel
function cancelSellerOffer(uint256 offerId) external {
claimed[msg.sender][offerId] = MAX_UINT256;
emit OfferCancelled(msg.sender, offerId);
}
function _ensureCorrectSigner(
address from,
address token,
uint256[] memory auctionData,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory signature,
SignatureType signatureType,
bool eip712
) internal view returns (address) {
bytes memory dataToHash;
if(eip712) {
dataToHash = abi.encodePacked(
"\x19\x01",
domainSeparator(),
_hashAuction(from, token, auctionData, ids, amounts)
);
} else {
dataToHash = _encodeBasicSignatureHash(from, token, auctionData, ids, amounts);
}
if (signatureType == SignatureType.EIP1271) {
require(
ERC1271(from).isValidSignature(dataToHash, signature) == ERC1271_MAGICVALUE,
"invalid 1271 signature"
);
} else if(signatureType == SignatureType.EIP1654){
require(
ERC1654(from).isValidSignature(keccak256(dataToHash), signature) == ERC1654_MAGICVALUE,
"invalid 1654 signature"
);
} else {
address signer = SigUtil.recover(keccak256(dataToHash), signature);
require(signer == from, "signer != from");
}
}
function _encodeBasicSignatureHash(
address from,
address token,
uint256[] memory auctionData,
uint256[] memory ids,
uint256[] memory amounts
) internal view returns (bytes memory) {
return SigUtil.prefixed(keccak256(abi.encodePacked(
address(this),
AUCTION_TYPEHASH,
from,
token,
auctionData[AuctionData_OfferId],
auctionData[AuctionData_StartingPrice],
auctionData[AuctionData_EndingPrice],
auctionData[AuctionData_StartedAt],
auctionData[AuctionData_Duration],
auctionData[AuctionData_Packs],
keccak256(abi.encodePacked(ids)),
keccak256(abi.encodePacked(amounts))
)));
}
function _hashAuction(
address from,
address token,
uint256[] memory auctionData,
uint256[] memory ids,
uint256[] memory amounts
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
AUCTION_TYPEHASH,
from,
token,
auctionData[AuctionData_OfferId],
auctionData[AuctionData_StartingPrice],
auctionData[AuctionData_EndingPrice],
auctionData[AuctionData_StartedAt],
auctionData[AuctionData_Duration],
auctionData[AuctionData_Packs],
keccak256(abi.encodePacked(ids)),
keccak256(abi.encodePacked(amounts))
)
);
}
}
| @notice claim offer using Basic Signature @param buyer address paying for the offer @param seller address of the seller @param token token used for payment @param purchase buyAmount, maxTokenAmount @param auctionData offerId, startingPrice, endingPrice, startedAt, duration, packs @param ids ids of the Assets being sold @param amounts amounts of Assets per pack @param signature signature of seller | function claimSellerOfferUsingBasicSig(
address buyer,
address payable seller,
address token,
uint256[] calldata auctionData,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata signature
) external payable {
_verifyParameters(
buyer,
seller,
token,
purchase[0],
auctionData,
ids,
amounts
);
_ensureCorrectSigner(seller, token, auctionData, ids, amounts, signature, SignatureType.DIRECT, false);
_executeDeal(
token,
purchase,
buyer,
seller,
auctionData,
ids,
amounts
);
}
| 918,034 | [
1,
14784,
10067,
1450,
7651,
9249,
225,
27037,
1758,
8843,
310,
364,
326,
10067,
225,
29804,
1758,
434,
326,
29804,
225,
1147,
1147,
1399,
364,
5184,
225,
23701,
30143,
6275,
16,
943,
1345,
6275,
225,
279,
4062,
751,
10067,
548,
16,
5023,
5147,
16,
11463,
5147,
16,
5746,
861,
16,
3734,
16,
2298,
87,
225,
3258,
3258,
434,
326,
26284,
3832,
272,
1673,
225,
30980,
30980,
434,
26284,
1534,
2298,
225,
3372,
3372,
434,
29804,
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,
7516,
22050,
10513,
7736,
8252,
8267,
12,
203,
3639,
1758,
27037,
16,
203,
3639,
1758,
8843,
429,
29804,
16,
203,
3639,
1758,
1147,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
279,
4062,
751,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
3258,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
30980,
16,
203,
3639,
1731,
745,
892,
3372,
203,
565,
262,
3903,
8843,
429,
288,
203,
3639,
389,
8705,
2402,
12,
203,
5411,
27037,
16,
203,
5411,
29804,
16,
203,
5411,
1147,
16,
203,
5411,
23701,
63,
20,
6487,
203,
5411,
279,
4062,
751,
16,
203,
5411,
3258,
16,
203,
5411,
30980,
203,
3639,
11272,
203,
3639,
389,
15735,
16147,
15647,
12,
1786,
749,
16,
1147,
16,
279,
4062,
751,
16,
3258,
16,
30980,
16,
3372,
16,
9249,
559,
18,
17541,
16,
629,
1769,
203,
3639,
389,
8837,
758,
287,
12,
203,
5411,
1147,
16,
203,
5411,
23701,
16,
203,
5411,
27037,
16,
203,
5411,
29804,
16,
203,
5411,
279,
4062,
751,
16,
203,
5411,
3258,
16,
203,
5411,
30980,
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,
-100,
-100,
-100,
-100,
-100,
-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-01-26
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
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/Address.sol
/**
* @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/introspection/IERC165.sol
/**
* @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/utils/introspection/ERC165.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;
}
}
// File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.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);
}
// File: @openzeppelin/contracts/token/ERC1155/IERC1155.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;
}
// File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.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);
}
// File: @openzeppelin/contracts/token/ERC1155/ERC1155.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() {
}
/**
* @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;
}
}
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;
}
/**
* @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 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);
}
}
contract MGDCbreedBAYC is ERC1155, Ownable {
string public constant name = "Bored Kid";
string public constant symbol = "BKid";
uint256 public NFTPrice = 250000000000000000;
using SafeMath for uint256;
using Strings for uint256;
uint256 public totalSupply = 0;
string private baseURI;
string private blindURI;
bool public reveal;
bool public isActive;
mapping(uint256 => bool) public hasBreed;
uint256 public giveawayCount;
IERC721 public MGDC=IERC721(0x0191c41DBceB20a612b25137133ca719E84f7933);
IERC721 public BAYC=IERC721(0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D);
mapping(uint256 => bool) public MGDCisBreeding;
uint256 public MGDCisBreedingCount;
mapping(uint256 => uint256) public MGDCbreeding;
/*
* Function to reveal all NFTs
*/
function revealNow()
external
onlyOwner
{
reveal = true;
}
/*
* Function to mint NFTs
*/
function mint(address to, uint32 count) internal {
if (count > 1) {
uint256[] memory ids = new uint256[](uint256(count));
uint256[] memory amounts = new uint256[](uint256(count));
for (uint32 i = 0; i < count; i++) {
ids[i] = totalSupply + i;
amounts[i] = 1;
}
_mintBatch(to, ids, amounts, "");
} else {
_mint(to, totalSupply, 1, "");
}
totalSupply += count;
}
/*
* Function setIsActive to activate/desactivate the smart contract
*/
function setIsActive(
bool _isActive
)
external
onlyOwner
{
isActive = _isActive;
}
/*
* Function to set Base and Blind URI
*/
function setURIs(
string memory _blindURI,
string memory _URI
)
external
onlyOwner
{
blindURI = _blindURI;
baseURI = _URI;
}
function listBreeding(
//uint256 idFirst,
uint256 idSecond
)
external
payable
{
require(NFTPrice == msg.value, "Ether value sent is not correct");
require(MGDC.ownerOf(idSecond)==msg.sender,"You don't own this BAYC nor this MGDC");
if(MGDC.ownerOf(idSecond)==msg.sender){
require(MGDCisBreeding[idSecond]==false);
MGDCisBreeding[idSecond]=true;
MGDCbreeding[MGDCisBreedingCount]=idSecond;
MGDCisBreedingCount=MGDCisBreedingCount+1;
}
}
/*
* Function to mint new NFTs when breeding
*/
function breed(
uint256 idSecond
)
public
payable
{
require(NFTPrice == msg.value, "Ether value sent is not correct");
require(isActive, "Contract is not active");
require(BAYC.balanceOf(msg.sender)>=1,"You are not BAYC");
require(!hasBreed[idSecond],"1 MGDC can breed only once");
require(MGDCisBreeding[idSecond],"this MGDC is not listed");
mint(msg.sender,1);
mint(MGDC.ownerOf(idSecond),1);
hasBreed[idSecond]=true;
}
/*
* Function to mint all NFTs to create the collection
*/
function mintByOwner(
address _to
)
public
onlyOwner
{
require(giveawayCount.add(1)<=1,"Cannot do more giveaway");
mint(_to,1);
giveawayCount=giveawayCount.add(1);
}
/*
* Function to get token URI of given token ID
*/
function uri(
uint256 _tokenId
)
public
view
virtual
override
returns (string memory)
{
require(_tokenId<totalSupply, "ERC1155Metadata: URI query for nonexistent token");
if (!reveal) {
return string(abi.encodePacked(blindURI));
} else {
return string(abi.encodePacked(baseURI, _tokenId.toString()));
}
}
/*
* Function to withdraw collected amount during minting by the owner
*/
function withdraw(
)
public
onlyOwner
{
uint balance = address(this).balance;
payable(address(0xbD7D5f86f2343aDe4108b638F34f01ad1986b8A5)).transfer(balance);
}
} | * @dev Implementation of the basic standard multi-token. _Available since v3.1._/ Mapping from token ID to account balances Mapping from account to operator approvals Used as the URI for all token types by relying on ID substitution, e.g. https:token-cdn-domain/{id}.json | contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
mapping(uint256 => mapping(address => uint256)) private _balances;
mapping(address => mapping(address => bool)) private _operatorApprovals;
string private _uri;
}
constructor() {
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
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];
}
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;
}
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;
}
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);
}
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
) internal virtual {}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
} catch Error(string memory reason) {
} catch {
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");
}
revert(reason);
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");
}
revert(reason);
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");
}
revert(reason);
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
} catch Error(string memory reason) {
} catch {
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
| 2,035,965 | [
1,
13621,
434,
326,
5337,
4529,
3309,
17,
2316,
18,
389,
5268,
3241,
331,
23,
18,
21,
6315,
19,
9408,
628,
1147,
1599,
358,
2236,
324,
26488,
9408,
628,
2236,
358,
3726,
6617,
4524,
10286,
487,
326,
3699,
364,
777,
1147,
1953,
635,
283,
6291,
603,
1599,
12785,
16,
425,
18,
75,
18,
2333,
30,
2316,
17,
20902,
17,
4308,
4938,
350,
5496,
1977,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
4232,
39,
2499,
2539,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
2499,
2539,
16,
467,
654,
39,
2499,
2539,
2277,
3098,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
565,
533,
3238,
389,
1650,
31,
203,
203,
97,
203,
203,
565,
3885,
1435,
288,
203,
540,
203,
565,
289,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
12,
654,
39,
28275,
16,
467,
654,
39,
28275,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
2499,
2539,
2934,
5831,
548,
747,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
2499,
2539,
2277,
3098,
2934,
5831,
548,
747,
203,
5411,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
2003,
12,
11890,
5034,
13,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
1650,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
16,
2254,
5034,
612,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
2499,
2539,
30,
11013,
843,
364,
326,
3634,
1758,
8863,
203,
3639,
327,
389,
2
] |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Context.sol
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/introspection/IERC165.sol
pragma solidity >=0.6.0 <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/IERC721.sol
pragma solidity >=0.6.2 <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/IERC721Metadata.sol
pragma solidity >=0.6.2 <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/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @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);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <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/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// 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/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/utils/EnumerableSet.sol
pragma solidity >=0.6.0 <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;
// 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];
}
// 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);
}
// 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))));
}
// 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/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` 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);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// 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;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @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 _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @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 || ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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);
_holderTokens[to].add(tokenId);
_tokenOwners.set(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); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(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"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @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()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <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 () internal {
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;
}
}
// PIXMONS CONTRACT
pragma solidity ^0.7.0;
pragma abicoder v2;
contract PixMons is ERC721, Ownable {
using SafeMath for uint256;
string public PIXMON_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN PIXMONS ARE ALL SOLD OUT
string public LICENSE_TEXT = ""; // IT IS WHAT IT SAYS
bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE
uint256 public constant pixmonPrice = 30000000000000000; // 0.03 ETH
uint public constant maxPixmonPurchase = 20;
uint256 public constant MAX_PIXMONS = 512;
bool public saleIsActive = false;
mapping(uint => string) public pixmonNames;
// Reserve 25 PIXMONS for team - Giveaways/Prizes etc
uint public pixmonReserve = 25;
event pixmonNameChange(address _by, uint _tokenId, string _name);
event licenseisLocked(string _licenseText);
constructor() ERC721("PixMons", "PM") { }
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function reservePixmons(address _to, uint256 _reserveAmount) public onlyOwner {
uint supply = totalSupply();
require(_reserveAmount > 0 && _reserveAmount <= pixmonReserve, "Not enough reserve left for team");
for (uint i = 0; i < _reserveAmount; i++) {
_safeMint(_to, supply + i);
}
pixmonReserve = pixmonReserve.sub(_reserveAmount);
}
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
PIXMON_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
// Returns the license for tokens
function tokenLicense(uint _id) public view returns(string memory) {
require(_id < totalSupply(), "CHOOSE A PIXMON WITHIN RANGE");
return LICENSE_TEXT;
}
// Locks the license to prevent further changes
function lockLicense() public onlyOwner {
licenseLocked = true;
emit licenseisLocked(LICENSE_TEXT);
}
// Change the license
function changeLicense(string memory _license) public onlyOwner {
require(licenseLocked == false, "License already locked");
LICENSE_TEXT = _license;
}
function mintPixmon(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint a Pixmon");
require(numberOfTokens > 0 && numberOfTokens <= maxPixmonPurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_PIXMONS, "Purchase would exceed max supply of Pixmons");
require(msg.value >= pixmonPrice.mul(numberOfTokens), "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_PIXMONS) {
_safeMint(msg.sender, mintIndex);
}
}
}
function changePixmonName(uint _tokenId, string memory _name) public {
require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this pixmon!");
require(sha256(bytes(_name)) != sha256(bytes(pixmonNames[_tokenId])), "New name is same as the current one");
pixmonNames[_tokenId] = _name;
emit pixmonNameChange(msg.sender, _tokenId, _name);
}
function viewPixmonName(uint _tokenId) public view returns( string memory ){
require( _tokenId < totalSupply(), "Choose a pixmon within range" );
return pixmonNames[_tokenId];
}
// GET ALL PIXMONS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH
function pixmonNamesOfOwner(address _owner) external view returns(string[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new string[](0);
} else {
string[] memory result = new string[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = pixmonNames[ tokenOfOwnerByIndex(_owner, index) ] ;
}
return result;
}
}
} | Returns the license for tokens | function tokenLicense(uint _id) public view returns(string memory) {
require(_id < totalSupply(), "CHOOSE A PIXMON WITHIN RANGE");
return LICENSE_TEXT;
}
| 13,638,841 | [
1,
1356,
326,
8630,
364,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1147,
13211,
12,
11890,
389,
350,
13,
1071,
1476,
1135,
12,
1080,
3778,
13,
288,
203,
3639,
2583,
24899,
350,
411,
2078,
3088,
1283,
9334,
315,
22213,
51,
1090,
432,
7024,
60,
17667,
13601,
706,
534,
8357,
8863,
203,
3639,
327,
511,
2871,
23396,
67,
5151,
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
] |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./utils/AccessControlled.sol";
import "./items/Commodity.sol";
import "./interfaces/IGalacticTransitAuthority.sol";
/**
* @title Galactic Transit Authority (GTA)
*
* @notice The GTA handles spaceship ownership, fuel and travel
*/
contract GalacticTransitAuthority is ERC721, AccessControlled, IGalacticTransitAuthority {
using SafeMath for uint;
struct Spaceship {
string name;
uint8 currentPlanet;
uint maxCargo; // in kg
uint currentFuel; // in litres
uint maxFuel;
}
uint public constant costOfSpaceship = 0.01 ether;
// How much fuel is used to travel between planets
uint public constant fuelUsage = 20;
uint public constant refuelCost = 10000000000000000;
// Number of spaceships in existence
uint numSpaceships;
// Mapping of address to spaceship struct
mapping(address => Spaceship) public addressToSpaceship;
// Resolves to true if account owns an address
mapping(address => bool) public addressOwnsSpaceship;
event SpaceshipBought(address owner, uint tokenId);
event TravelComplete(address player, uint8 planetId, uint currentFuel);
event RefuelComplete(address player);
modifier onlyPlayer() {
require(isPlayer(msg.sender), "You need to own a spaceship to call this function");
_;
}
/**
* @notice Creates a spaceship and assigns ownership to sender
* @dev Spaceship ownership is a prerequisite for owning commodities
* @param _name What to name your spaceship
*/
function buySpaceship(string _name) external payable {
require(msg.value == costOfSpaceship, "You need to provide the correct amount of ether");
require(balanceOf(msg.sender) == 0, "Accounts can only own one spaceship (for now)");
numSpaceships = numSpaceships.add(1);
uint _tokenId = numSpaceships;
_mint(msg.sender, _tokenId);
addressToSpaceship[msg.sender] = Spaceship(_name, 255, 90000, 100, 100);
addressOwnsSpaceship[msg.sender] = true;
emit SpaceshipBought(msg.sender, _tokenId);
}
/**
* @notice Changes spaceship's current planet to planet specified
* @dev This function is responsible for deciding which planet IDs are valid planets
* @param _planetId Id of planet to travel to (0 - 6), or 255 for the 8th planet
*/
function travelToPlanet(uint8 _planetId) external onlyPlayer {
require((0 <= _planetId && _planetId <= 6) || _planetId == 255, "planetId must be between 0 and 6, inclusive, or be equal to 255");
require(addressToSpaceship[msg.sender].currentFuel >= fuelUsage, "You do not have enough fuel to travel");
addressToSpaceship[msg.sender].currentPlanet = _planetId;
addressToSpaceship[msg.sender].currentFuel = addressToSpaceship[msg.sender].currentFuel.sub(fuelUsage);
emit TravelComplete(msg.sender, _planetId, addressToSpaceship[msg.sender].currentFuel);
}
/**
* @notice Changes spaceship's current fuel to max fuel, for a fee in ether
* @dev Throws if cost to refuel is not provided
*/
function refuel() external payable onlyPlayer {
require(msg.value >= refuelCost, "You need to provide the correct amount of ether to refuel");
addressToSpaceship[msg.sender].currentFuel = addressToSpaceship[msg.sender].maxFuel;
}
/**
* @notice Returns player's spaceship info
*/
function getInfo() external view returns (
string spaceshipName,
uint8 currentPlanet,
uint maxCargo,
uint currentFuel,
uint maxFuel
) {
return (
addressToSpaceship[msg.sender].name,
addressToSpaceship[msg.sender].currentPlanet,
addressToSpaceship[msg.sender].maxCargo,
addressToSpaceship[msg.sender].currentFuel,
addressToSpaceship[msg.sender].maxFuel
);
}
function isPlayer(address _address) public view returns (bool) {
return addressOwnsSpaceship[_address];
}
function getCurrentPlanet(address _address) public view returns (uint8) {
return addressToSpaceship[_address].currentPlanet;
}
function checkFuel(address _address) public view returns (uint currentFuel, uint maxFuel) {
return (
addressToSpaceship[_address].currentFuel,
addressToSpaceship[_address].maxFuel
);
}
function getMaxCargo(address _address) public view returns (uint) {
return addressToSpaceship[_address].maxCargo;
}
function getAvailableCargo(address _address, uint _currentCargo) external view returns (uint) {
return getMaxCargo(_address).sub(_currentCargo);
}
function canFitCargo(address _player, uint _currentCargo, uint _incomingCargo) external returns (bool) {
uint _maxCargo = getMaxCargo(_player);
uint _cargoAvailable = _maxCargo.sub(_currentCargo);
return _cargoAvailable >= _incomingCargo;
}
function() public {}
}
| * @notice Creates a spaceship and assigns ownership to sender @dev Spaceship ownership is a prerequisite for owning commodities @param _name What to name your spaceship/ | function buySpaceship(string _name) external payable {
require(msg.value == costOfSpaceship, "You need to provide the correct amount of ether");
require(balanceOf(msg.sender) == 0, "Accounts can only own one spaceship (for now)");
numSpaceships = numSpaceships.add(1);
uint _tokenId = numSpaceships;
_mint(msg.sender, _tokenId);
addressToSpaceship[msg.sender] = Spaceship(_name, 255, 90000, 100, 100);
addressOwnsSpaceship[msg.sender] = true;
emit SpaceshipBought(msg.sender, _tokenId);
}
| 1,027,716 | [
1,
2729,
279,
7292,
5310,
471,
22698,
23178,
358,
5793,
225,
348,
4996,
5310,
23178,
353,
279,
30328,
16608,
1137,
364,
25022,
1543,
369,
1961,
225,
389,
529,
18734,
358,
508,
3433,
7292,
5310,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
30143,
12077,
5310,
12,
1080,
389,
529,
13,
3903,
8843,
429,
288,
203,
565,
2583,
12,
3576,
18,
1132,
422,
6991,
951,
12077,
5310,
16,
315,
6225,
1608,
358,
5615,
326,
3434,
3844,
434,
225,
2437,
8863,
203,
565,
2583,
12,
12296,
951,
12,
3576,
18,
15330,
13,
422,
374,
16,
315,
13971,
848,
1338,
4953,
1245,
7292,
5310,
261,
1884,
2037,
2225,
1769,
203,
565,
818,
12077,
5310,
87,
273,
818,
12077,
5310,
87,
18,
1289,
12,
21,
1769,
203,
565,
2254,
389,
2316,
548,
273,
818,
12077,
5310,
87,
31,
203,
565,
389,
81,
474,
12,
3576,
18,
15330,
16,
389,
2316,
548,
1769,
203,
565,
1758,
774,
12077,
5310,
63,
3576,
18,
15330,
65,
273,
348,
4996,
5310,
24899,
529,
16,
4561,
16,
2468,
2787,
16,
2130,
16,
2130,
1769,
203,
565,
1758,
3494,
2387,
12077,
5310,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
565,
3626,
348,
4996,
5310,
13809,
9540,
12,
3576,
18,
15330,
16,
389,
2316,
548,
1769,
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
] |
./partial_match/3/0xB404C889889Ab5e8186BFCD6A7C1DA05a68EEEe2/sources/FlamingFarm.sol | FlamingFarm with Governance. | contract FlamingFarm is ERC20("Flaming Farm", "FFARM"), Ownable {
uint256 private _totalLock;
mapping (address => bool) public minters;
uint256 private _cap = 500000000e18;
uint256 public _totalSupply;
uint256 public lockFromBlock;
uint256 public lockToBlock;
mapping(address => uint256) private _locks;
mapping(address => uint256) private _lastUnlockBlock;
event Lock(address indexed to, uint256 value);
constructor(uint256 _lockFromBlock, uint256 _lockToBlock) public {
lockFromBlock = _lockFromBlock;
lockToBlock = _lockToBlock;
}
function cap() public view returns (uint256) {
return _cap;
}
function mint(address to, uint amount) public onlyMinter {
_mint(to, amount);
}
function burn(uint amount) public {
require(amount > 0);
require(balanceOf(msg.sender) >= amount);
_burn(msg.sender, amount);
}
function addMinter(address account) public onlyOwner {
minters[account] = true;
}
function removeMinter(address account) public onlyOwner {
minters[account] = false;
}
modifier onlyMinter() {
require(minters[msg.sender], "Restricted to minters.");
_;
}
} | 5,066,887 | [
1,
2340,
7772,
42,
4610,
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,
3857,
7772,
42,
4610,
353,
4232,
39,
3462,
2932,
2340,
7772,
478,
4610,
3113,
315,
2246,
26120,
6,
3631,
14223,
6914,
288,
203,
565,
2254,
5034,
3238,
389,
4963,
2531,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
1131,
5432,
31,
203,
565,
2254,
5034,
3238,
389,
5909,
273,
1381,
12648,
73,
2643,
31,
203,
565,
2254,
5034,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2254,
5034,
1071,
2176,
1265,
1768,
31,
203,
565,
2254,
5034,
1071,
2176,
774,
1768,
31,
203,
377,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
23581,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
2722,
7087,
1768,
31,
203,
377,
203,
565,
871,
3488,
12,
2867,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
565,
3885,
12,
11890,
5034,
389,
739,
1265,
1768,
16,
2254,
5034,
389,
739,
774,
1768,
13,
1071,
288,
203,
3639,
2176,
1265,
1768,
273,
389,
739,
1265,
1768,
31,
203,
3639,
2176,
774,
1768,
273,
389,
739,
774,
1768,
31,
203,
565,
289,
203,
377,
203,
565,
445,
3523,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
5909,
31,
203,
565,
289,
203,
7010,
565,
445,
312,
474,
12,
2867,
358,
16,
2254,
3844,
13,
1071,
1338,
49,
2761,
288,
203,
3639,
389,
81,
474,
12,
869,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
11890,
3844,
13,
1071,
288,
203,
3639,
2583,
12,
8949,
405,
374,
1769,
203,
3639,
2
] |
pragma solidity ^0.4.0;
// interfaces in solodity
interface Regulator
{
// check if we have enough founds
function checkValue(uint amount) returns (bool);
}
// a contract in this case is a class
// in solidity classes does not exists anymore
// instead we have contracts
// Back is inherit from Regulator interface
contract Bank is Regulator
{
// cant be access from outside, just for
// bank itself and children
uint internal myInternalValue;
// cant be accessed from children
uint private value;
// addresses
// this will be the owner of the contract
address private owner;
modifier ownerFunc
{
// owner base functionality
require(owner == msg.sender);
_; // to be able to execute this function
}
//constructors
function Bank(uint amount)
{
// will be called just once
value = amount;
owner = msg.sender;
}
// set the ownerFunc
// which means no one except the owner of the contract can
// access these functions
function deposit(uint amount) internal ownerFunc
{
value += amount;
}
function withDraw(uint amount) private ownerFunc
{
if(checkValue(amount))
{
value -= amount;
}
}
function balance() returns (uint)
{
return value;
}
// like a virtual function
// or a abstract function that can be implemented in
// children
//function loan() returns (bool);
function checkValue(uint amount) returns (bool)
{
// check deposit
return value >= amount;
}
function loan() returns (bool)
{
return value > 0;
}
}
// we can set a value at the moment of initialize the bank object that
// this class inherit
contract contractLevelOne is Bank(10) {
// encapsulation
string private name;
uint private age;
function setName(string newName)
{
name = newName;
}
function getName() returns (string)
{
return name;
}
function setAge(uint newAge)
{
age = newAge;
}
function getAge() returns (uint)
{
return age;
}
}
// Error handling
contract TestThrows
{
function testAssert()
{
//
assert(1 == 2);
}
function testRequire()
{
// parameter requirement
require(2 == 1);
}
function testRevert()
{
// should revert the gas consumption
// we use in a message
revert();
}
function testThrow()
{
// this comsumes all the gas
throw; // actually it is deprecated
}
} | this comsumes all the gas | function testThrow()
{
}
| 7,234,442 | [
1,
2211,
532,
1364,
281,
777,
326,
16189,
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,
1842,
8282,
1435,
203,
565,
288,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.0 <0.7.0;
import "@chainlink/contracts/src/v0.4/ChainlinkClient.sol";
import "@chainlink/contracts/src/v0.4/vendor/Ownable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
contract JagerGitClient is ChainlinkClient, Ownable {
uint256 constant private ORACLE_PAYMENT = 1 * LINK;
address _oracle;
string _jobId;
string url1;
string url2;
bytes32 public addrStr;
/**
* @dev Details of each transfer
* @param contract_ contract address of ER20 token to transfer
* @param to_ receiving account
* @param amount_ number of tokens to transfer to_ account
* @param failed_ if transfer was successful or not
*/
struct Transfer {
address contract_;
address to_;
uint amount_;
bool failed_;
}
event requestBountyCompleteFulfilled(
bytes32 indexed requestId,
bytes32 indexed addrStr
);
/**
* @dev a mapping from transaction ID's to the sender address
* that initiates them. Owners can create several transactions
*/
mapping(address => uint[]) public transactionIndexesToSender;
/**
* @dev a list of all transfers successful or unsuccessful
*/
address public owner;
/**
* @dev list of all supported tokens for transfer
* @param string token symbol
* @param address contract address of token
*/
mapping(bytes32 => address) public tokens;
ERC20 public ERC20Interface;
Transfer[] public transactions;
/**
* @dev Event to notify if transfer successful or failed
* after account approval verified
*/
event TransferSuccessful(address indexed from_, address indexed to_, uint256 amount_);
event TransferFailed(address indexed from_, address indexed to_, uint256 amount_);
/**
* @dev add address of token to list of supported tokens using
* token symbol as identifier in mapping
*/
function addNewToken(bytes32 symbol_, address address_) public onlyOwner returns (bool) {
tokens[symbol_] = address_;
return true;
}
/**
* @dev remove address of token we no more support
*/
function removeToken(bytes32 symbol_) public onlyOwner returns (bool) {
require(tokens[symbol_] != 0x0);
delete(tokens[symbol_]);
return true;
}
/**
* @dev method that handles transfer of ERC20 tokens to other address
* it assumes the calling address has approved this contract
* as spender
* @param symbol_ identifier mapping to a token contract address
* @param to_ beneficiary address
* @param amount_ numbers of token to transfer
*/
function transferTokens(bytes32 symbol_, address to_, uint256 amount_) public {
require(tokens[symbol_] != 0x0);
require(amount_ > 0);
address contract_ = tokens[symbol_];
address from_ = msg.sender;
ERC20Interface = ERC20(contract_);
uint256 transactionId = transactions.push(
Transfer({
contract_: contract_,
to_: to_,
amount_: amount_,
failed_: true
})
);
transactionIndexesToSender[from_].push(transactionId - 1);
if(amount_ > ERC20Interface.allowance(from_, address(this))) {
emit TransferFailed(from_, to_, amount_);
revert();
}
ERC20Interface.transferFrom(from_, to_, amount_);
transactions[transactionId - 1].failed_ = false;
emit TransferSuccessful(from_, to_, amount_);
}
/**
* @dev withdraw funds from this contract
* @param beneficiary address to receive ether
*/
function withdraw(address beneficiary) public payable onlyOwner {
beneficiary.transfer(address(this).balance);
}
function cashReward(bytes32 symbol_, address to_, uint256 amount_) public {
require(tokens[symbol_] != 0x0);
require(amount_ > 0);
address contract_ = tokens[symbol_];
ERC20Interface = ERC20(contract_);
uint256 transactionId = transactions.push(
Transfer({
contract_: contract_,
to_: to_,
amount_: amount_,
failed_: true
})
);
if(amount_ > ERC20Interface.balanceOf(address(this))) {
emit TransferFailed(address(this), to_, amount_);
revert();
}
ERC20Interface.transferFrom(address(this), to_, amount_);
transactions[transactionId - 1].failed_ = false;
emit TransferSuccessful(address(this), to_, amount_);
}
uint256 reward_pool;
struct Bounty {
uint id;
string repo_link;
string tag;
uint reward_amount;
bool active;
string title;
string description;
}
struct Meister {
address id;
uint bounties_fulfilled;
}
uint[] public bountyIDs;
address[] public allMeisters;
mapping (address => uint[]) public meister_bounty_ids;
mapping (string => uint[]) private repo_bounties;
mapping (uint => Bounty) public bounties;
event NewBounty(uint _bounty_id, address _owner, uint _reward);
constructor() public Ownable() {
setPublicChainlinkToken();
_oracle = address(0x56dd6586DB0D08c6Ce7B2f2805af28616E082455);
_jobId = "c128fbb0175442c8ba828040fdd1a25e";
bytes32 b = stringToBytes32("DAI");
addNewToken(b, address(0x4dC966317B2c55105FAd4835F651022aCD632120));
url1 = "https://api.github.com/repos/";
url2 = "/pulls/";
}
function AddNewMeister() private {
allMeisters.push(msg.sender);
}
function CreateBounty(string memory repoLink,
uint reward,
string PR_tag,
string title,
string description) public returns (uint bountyID) {
Bounty memory bounty = Bounty({
id: bountyIDs.length,
repo_link: repoLink,
tag: PR_tag,
reward_amount: reward,
active: true,
title: title,
description: description
});
uint len = repo_bounties[repoLink].length;
if(len != 0) {
for(uint i = 0; i < len; i++) {
uint id = repo_bounties[repoLink][i];
require(compare(bounties[id].tag, PR_tag) != 0 || !bounties[id].active);
}
}
repo_bounties[repoLink].push(bounty.id);
if (meister_bounty_ids[msg.sender].length == 0) {
AddNewMeister();
}
meister_bounty_ids[msg.sender].push(bounty.id);
bountyIDs.push(bounty.id);
bounties[bounty.id] = bounty;
return bounty.id;
}
function GetMeisterBounties(address meister) public view returns (uint[] memory bountyIds) {
return meister_bounty_ids[meister];
}
function GetRepoBounties(string repoLink) public view returns (uint[] memory bountyIds) {
return repo_bounties[repoLink];
}
function GetBountyInfo(uint bountyId) public view returns (uint id,
string memory repoLink,
string memory tag,
uint reward,
bool active,
string memory title,
string memory description) {
Bounty memory bounty = bounties[bountyId];
return (bounty.id,
bounty.repo_link,
bounty.tag,
bounty.reward_amount,
bounty.active,
bounty.title,
bounty.description);
}
function getChainlinkToken() public view returns (address) {
return chainlinkTokenAddress();
}
function withdrawLink() public onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer");
}
function cancelRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunctionId,
uint256 _expiration
)
public
onlyOwner
{
cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration);
}
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly { // solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
}
function compare(string _a, string _b) private pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
//@todo unroll the loop into increments of 32 and do full 32 byte comparisons
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function requestBountyComplete(string repo_link, string PR_id)
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_jobId), this, this.fulfillBountyComplete.selector);
req.add("get", string(abi.encodePacked(url1, repo_link, url2, PR_id)));
req.add("path", "body");
sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT);
}
function fulfillBountyComplete(bytes32 _requestId, bytes32 _addrStr)
public
recordChainlinkFulfillment(_requestId)
{
emit requestBountyCompleteFulfilled(_requestId, _addrStr);
addrStr = _addrStr;
}
}
| * @dev list of all supported tokens for transfer @param string token symbol @param address contract address of token/ | mapping(bytes32 => address) public tokens;
| 999,045 | [
1,
1098,
434,
777,
3260,
2430,
364,
7412,
225,
533,
1147,
3273,
225,
1758,
6835,
1758,
434,
1147,
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
] | [
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,
0,
0
] | [
1,
225,
2874,
12,
3890,
1578,
516,
1758,
13,
1071,
2430,
31,
7010,
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
] |
./partial_match/1/0xA55d9ef16Af921b70Fed1421C1D298Ca5A3a18F1/sources/StdReferenceBasic.sol | BandChain request identifier for this data.
| uint64 requestID; | 2,872,853 | [
1,
14231,
3893,
590,
2756,
364,
333,
501,
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
] | [
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,
2254,
1105,
590,
734,
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
] |
./partial_match/5/0xF549C95Cd7aE153bb194e9dE250E4D7963e1aCDc/sources/DigitalaxLPStaking.sol | @notice Unstake without caring about rewards. EMERGENCY ONLY. | function emergencyUnstake()
public
{
lpToken.safeTransfer(address(msg.sender), stakers[msg.sender].balance);
emit EmergencyUnstake(msg.sender, stakers[msg.sender].balance);
stakers[msg.sender].balance = 0;
stakers[msg.sender].rewardsEarned = 0;
}
| 16,849,137 | [
1,
984,
334,
911,
2887,
5926,
310,
2973,
283,
6397,
18,
7141,
654,
16652,
16068,
20747,
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
] | [
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,
801,
24530,
984,
334,
911,
1435,
7010,
3639,
1071,
203,
565,
288,
203,
3639,
12423,
1345,
18,
4626,
5912,
12,
2867,
12,
3576,
18,
15330,
3631,
384,
581,
414,
63,
3576,
18,
15330,
8009,
12296,
1769,
203,
3639,
3626,
512,
6592,
75,
2075,
984,
334,
911,
12,
3576,
18,
15330,
16,
384,
581,
414,
63,
3576,
18,
15330,
8009,
12296,
1769,
203,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
12296,
273,
374,
31,
203,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
266,
6397,
41,
1303,
329,
273,
374,
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
] |
pragma solidity ^0.5.0;
contract CryptoTycoonsVIPLib{
address payable public owner;
// Accumulated jackpot fund.
uint128 public jackpotSize;
uint128 public rankingRewardSize;
mapping (address => uint) userExpPool;
mapping (address => bool) public callerMap;
event RankingRewardPayment(address indexed beneficiary, uint amount);
modifier onlyOwner {
require(msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
modifier onlyCaller {
bool isCaller = callerMap[msg.sender];
require(isCaller, "onlyCaller methods called by non-caller.");
_;
}
constructor() public{
owner = msg.sender;
callerMap[owner] = true;
}
// Fallback function deliberately left empty. It's primary use case
// is to top up the bank roll.
function () external payable {
}
function kill() external onlyOwner {
selfdestruct(owner);
}
function addCaller(address caller) public onlyOwner{
bool isCaller = callerMap[caller];
if (isCaller == false){
callerMap[caller] = true;
}
}
function deleteCaller(address caller) external onlyOwner {
bool isCaller = callerMap[caller];
if (isCaller == true) {
callerMap[caller] = false;
}
}
function addUserExp(address addr, uint256 amount) public onlyCaller{
uint exp = userExpPool[addr];
exp = exp + amount;
userExpPool[addr] = exp;
}
function getUserExp(address addr) public view returns(uint256 exp){
return userExpPool[addr];
}
function getVIPLevel(address user) public view returns (uint256 level) {
uint exp = userExpPool[user];
if(exp >= 25 ether && exp < 125 ether){
level = 1;
} else if(exp >= 125 ether && exp < 250 ether){
level = 2;
} else if(exp >= 250 ether && exp < 1250 ether){
level = 3;
} else if(exp >= 1250 ether && exp < 2500 ether){
level = 4;
} else if(exp >= 2500 ether && exp < 12500 ether){
level = 5;
} else if(exp >= 12500 ether && exp < 25000 ether){
level = 6;
} else if(exp >= 25000 ether && exp < 125000 ether){
level = 7;
} else if(exp >= 125000 ether && exp < 250000 ether){
level = 8;
} else if(exp >= 250000 ether && exp < 1250000 ether){
level = 9;
} else if(exp >= 1250000 ether){
level = 10;
} else{
level = 0;
}
return level;
}
function getVIPBounusRate(address user) public view returns (uint256 rate){
uint level = getVIPLevel(user);
return level;
}
// This function is used to bump up the jackpot fund. Cannot be used to lower it.
function increaseJackpot(uint increaseAmount) external onlyCaller {
require (increaseAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + increaseAmount <= address(this).balance, "Not enough funds.");
jackpotSize += uint128(increaseAmount);
}
function payJackpotReward(address payable to) external onlyCaller{
to.transfer(jackpotSize);
jackpotSize = 0;
}
function getJackpotSize() external view returns (uint256){
return jackpotSize;
}
function increaseRankingReward(uint amount) public onlyCaller{
require (amount <= address(this).balance, "Increase amount larger than balance.");
require (rankingRewardSize + amount <= address(this).balance, "Not enough funds.");
rankingRewardSize += uint128(amount);
}
function payRankingReward(address payable to) external onlyCaller {
uint128 prize = rankingRewardSize / 2;
rankingRewardSize = rankingRewardSize - prize;
if(to.send(prize)){
emit RankingRewardPayment(to, prize);
}
}
function getRankingRewardSize() external view returns (uint128){
return rankingRewardSize;
}
}
contract HalfRouletteEvents {
event Commit(uint commit); // 11
event Payment(address indexed gambler, uint amount, uint8 betMask, uint8 l, uint8 r, uint betAmount); // 11 11
event Refund(address indexed gambler, uint amount); // 11 11
event JackpotPayment(address indexed gambler, uint amount); // 11
event VIPBenefit(address indexed gambler, uint amount); // VIP 11
event InviterBenefit(address indexed inviter, address gambler, uint amount, uint betAmount); // 111 11
}
contract CryptoTycoonsDApp {
address payable public owner; // 111
address payable nextOwner;
address secretSigner;
mapping(address => bool) public croupierMap; // 111 11
address payable public VIPLibraryAddress; // vip pool address
modifier onlyOwner {
require(msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
modifier onlyCroupier {
bool isCroupier = croupierMap[msg.sender];
require(isCroupier, "OnlyCroupier methods called by non-croupier.");
_;
}
constructor() public {
owner = msg.sender;
croupierMap[msg.sender] = true;
secretSigner = msg.sender;
}
function () external payable {}
function approveNextOwner(address payable _nextOwner) external onlyOwner {
require(_nextOwner != owner, "Cannot approve current owner.");
nextOwner = _nextOwner;
}
function acceptNextOwner() external {
require(msg.sender == nextOwner, "Can only accept preapproved new owner.");
owner = nextOwner;
}
function setSecretSigner(address newSecretSigner) external onlyOwner {
secretSigner = newSecretSigner;
}
function addCroupier(address newCroupier) external onlyOwner {
bool isCroupier = croupierMap[newCroupier];
if (isCroupier == false) {
croupierMap[newCroupier] = true;
}
}
function deleteCroupier(address newCroupier) external onlyOwner {
bool isCroupier = croupierMap[newCroupier];
if (isCroupier == true) {
croupierMap[newCroupier] = false;
}
}
function setVIPLibraryAddress(address payable addr) external onlyOwner {
VIPLibraryAddress = addr;
}
function getMyAccuAmount() external view returns (uint) {
CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress);
return vipLib.getUserExp(msg.sender);
}
function getJackpotSize() external view returns (uint) {
CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress);
return vipLib.getJackpotSize();
}
function getRankingRewardSize() external view returns (uint128) {
CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress);
return vipLib.getRankingRewardSize();
}
}
contract HalfRouletteStruct {
struct Bet {
uint amount; // 11 11
uint8 betMask; // 11 11
uint40 placeBlockNumber; // Block number of placeBet tx.
address payable gambler; // Address of a gambler, used to pay out winning bets.
}
}
contract HalfRouletteConstant {
// constant
// EVM BLOCKHASH opcode can query no further than 256 blocks into the
// past. Given that settleBet uses block hash of placeBet as one of
// complementary entropy sources, we cannot process bets older than this
// threshold. On rare occasions AceDice croupier may fail to invoke
// settleBet in this timespan due to technical issues or extreme Ethereum
// congestion; such bets can be refunded via invoking refundBet.
uint constant BET_EXPIRATION_BLOCKS = 250;
uint constant HOUSE_EDGE_PERCENT = 1; // amount * 0.01
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0004 ether; // 11 houseEdge
uint constant RANK_FUNDS_PERCENT = 7; // amount * 0.01 * 0.07
uint constant INVITER_BENEFIT_PERCENT = 7; // amount * 0.01 * 0.07
uint constant MIN_BET = 0.01 ether; // 11 11 11
uint constant MAX_BET = 300000 ether; // 11 11 11
uint constant MIN_JACKPOT_BET = 0.1 ether;
uint constant JACKPOT_FEE = 0.001 ether;
uint constant BASE_WIN_RATE = 100000;
}
contract HalfRoulettePure is HalfRouletteConstant {
function verifyBetMask(uint betMask) public pure {
bool verify;
assembly {
switch betMask
case 1 /* ODD */{verify := 1}
case 2 /* EVEN */{verify := 1}
case 4 /* LEFT */{verify := 1}
case 8 /* RIGHT */{verify := 1}
case 5 /* ODD | LEFT */{verify := 1}
case 9 /* ODD | RIGHT */{verify := 1}
case 6 /* EVEN | LEFT */{verify := 1}
case 10 /* EVEN | RIGHT */{verify := 1}
case 16 /* EQUAL */{verify := 1}
}
require(verify, "invalid betMask");
}
function getRecoverSigner(uint40 commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) public pure returns (address) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes memory message = abi.encodePacked(commitLastBlock, commit);
bytes32 messageHash = keccak256(abi.encodePacked(prefix, keccak256(message)));
return ecrecover(messageHash, v, r, s);
}
function getWinRate(uint betMask) public pure returns (uint rate) {
// assembly 1111 constant 11 11
uint ODD_EVEN_RATE = 50000;
uint LEFT_RIGHT_RATE = 45833;
uint MIX_ODD_RATE = 25000;
uint MIX_EVEN_RATE = 20833;
uint EQUAL_RATE = 8333;
assembly {
switch betMask
case 1 /* ODD */{rate := ODD_EVEN_RATE}
case 2 /* EVEN */{rate := ODD_EVEN_RATE}
case 4 /* LEFT */{rate := LEFT_RIGHT_RATE}
case 8 /* RIGHT */{rate := LEFT_RIGHT_RATE}
case 5 /* ODD | LEFT */{rate := MIX_ODD_RATE}
case 9 /* ODD | RIGHT */{rate := MIX_ODD_RATE}
case 6 /* EVEN | LEFT */{rate := MIX_EVEN_RATE}
case 10 /* EVEN | RIGHT */{rate := MIX_EVEN_RATE}
case 16 /* EQUAL */{rate := EQUAL_RATE}
}
}
function calcHouseEdge(uint amount) public pure returns (uint houseEdge) {
// 0.02
houseEdge = amount * HOUSE_EDGE_PERCENT / 100;
if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) {
houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT;
}
}
function calcJackpotFee(uint amount) public pure returns (uint jackpotFee) {
// 0.001
if (amount >= MIN_JACKPOT_BET) {
jackpotFee = JACKPOT_FEE;
}
}
function calcRankFundsFee(uint amount) public pure returns (uint rankFundsFee) {
// 0.01 * 0.07
rankFundsFee = amount * RANK_FUNDS_PERCENT / 10000;
}
function calcInviterBenefit(uint amount) public pure returns (uint invitationFee) {
// 0.01 * 0.07
invitationFee = amount * INVITER_BENEFIT_PERCENT / 10000;
}
function getWinAmount(uint betMask, uint amount) public pure returns (uint) {
uint houseEdge = calcHouseEdge(amount);
uint jackpotFee = calcJackpotFee(amount);
uint betAmount = amount - houseEdge - jackpotFee;
uint rate = getWinRate(betMask);
return betAmount * BASE_WIN_RATE / rate;
}
function calcBetResult(uint betMask, bytes32 entropy) public pure returns (bool isWin, uint l, uint r) {
uint v = uint(entropy);
l = (v % 12) + 1;
r = ((v >> 4) % 12) + 1;
uint mask = getResultMask(l, r);
isWin = (betMask & mask) == betMask;
}
function getResultMask(uint l, uint r) public pure returns (uint mask) {
uint v1 = (l + r) % 2;
if (v1 == 0) {
mask = mask | 2;
} else {
mask = mask | 1;
}
if (l == r) {
mask = mask | 16;
} else if (l > r) {
mask = mask | 4;
} else {
mask = mask | 8;
}
return mask;
}
function isJackpot(bytes32 entropy, uint amount) public pure returns (bool jackpot) {
return amount >= MIN_JACKPOT_BET && (uint(entropy) % 1000) == 0;
}
function verifyCommit(address signer, uint40 commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) internal pure {
address recoverSigner = getRecoverSigner(commitLastBlock, commit, v, r, s);
require(recoverSigner == signer, "failed different signer");
}
function startOfDay(uint timestamp) internal pure returns (uint64) {
return uint64(timestamp - (timestamp % 1 days));
}
}
contract HalfRoulette is CryptoTycoonsDApp, HalfRouletteEvents, HalfRouletteStruct, HalfRouletteConstant, HalfRoulettePure {
uint128 public lockedInBets;
// Adjustable max bet profit. Used to cap bets against dynamic odds.
uint public maxProfit = 10 ether;
// global variable
mapping(uint => Bet) public bets;
mapping(address => address payable) public inviterMap;
function () external payable {}
function kill() external onlyOwner {
require(lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct.");
selfdestruct(address(owner));
}
function setMaxProfit(uint _maxProfit) external onlyOwner {
require(_maxProfit < MAX_BET, "maxProfit should be a sane number.");
maxProfit = _maxProfit;
}
function placeBet(uint8 betMask, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) public payable {
Bet storage bet = bets[commit];
require(bet.gambler == address(0), "Bet should be in a 'clean' state.");
// amount checked
uint amount = msg.value;
require(amount >= MIN_BET, 'failed amount >= MIN_BET');
require(amount <= MAX_BET, "failed amount <= MAX_BET");
// allow bet check
verifyBetMask(betMask);
// rand seed check
verifyCommit(secretSigner, uint40(commitLastBlock), commit, v, r, s);
// house balance check
uint winAmount = getWinAmount(betMask, amount);
require(winAmount <= amount + maxProfit, "maxProfit limit violation.");
lockedInBets += uint128(winAmount);
require(lockedInBets <= address(this).balance, "Cannot afford to lose this bet.");
// save
emit Commit(commit);
bet.gambler = msg.sender;
bet.amount = amount;
bet.betMask = betMask;
bet.placeBlockNumber = uint40(block.number);
}
function placeBetWithInviter(uint8 betMask, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s, address payable inviter) external payable {
require(inviter != address(0), "inviter != address (0)");
address preInviter = inviterMap[msg.sender];
if (preInviter == address(0)) {
inviterMap[msg.sender] = inviter;
}
placeBet(betMask, commitLastBlock, commit, v, r, s);
}
function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
uint placeBlockNumber = bet.placeBlockNumber;
// Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS).
require(block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before.");
require(block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
require(blockhash(placeBlockNumber) == blockHash);
// Settle bet using reveal and blockHash as entropy sources.
settleBetCommon(bet, reveal, blockHash);
}
function processVIPBenefit(address gambler, uint amount) internal returns (uint benefitAmount) {
CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress);
uint rate = vipLib.getVIPBounusRate(gambler);
if (rate > 0) {
benefitAmount = amount * rate / 10000;
emit VIPBenefit(gambler, benefitAmount);
}
vipLib.addUserExp(gambler, amount);
}
function processJackpot(address payable gambler, bytes32 entropy, uint amount) internal returns (uint benefitAmount) {
if (isJackpot(entropy, amount)) {
CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress);
uint jackpotSize = vipLib.getJackpotSize();
vipLib.payJackpotReward(gambler);
benefitAmount = jackpotSize;
emit JackpotPayment(gambler, benefitAmount);
}
}
function processRoulette(address gambler, uint betMask, bytes32 entropy, uint amount) internal returns (uint benefitAmount) {
uint winAmount = getWinAmount(betMask, amount);
lockedInBets -= uint128(winAmount);
(bool isWin, uint l, uint r) = calcBetResult(betMask, entropy);
benefitAmount = isWin ? winAmount : 0;
emit Payment(gambler, benefitAmount, uint8(betMask), uint8(l), uint8(r), amount);
}
function processInviterBenefit(address gambler, uint betAmount) internal {
address payable inviter = inviterMap[gambler];
if (inviter != address(0)) {
uint inviterBenefit = calcInviterBenefit(betAmount);
if (inviter.send(inviterBenefit)) {
emit InviterBenefit(inviter, gambler, inviterBenefit, betAmount);
}
}
}
function transferCryptoTycoonsFee(uint amount) internal {
uint jackpotFee = calcJackpotFee(amount);
uint rankFundFee = calcRankFundsFee(amount);
CryptoTycoonsVIPLib vipLib = CryptoTycoonsVIPLib(VIPLibraryAddress);
VIPLibraryAddress.transfer(rankFundFee + jackpotFee);
vipLib.increaseRankingReward(rankFundFee);
if (jackpotFee > 0) {
vipLib.increaseJackpot(jackpotFee);
}
}
function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) internal {
uint amount = bet.amount;
// Check that bet is in 'active' state.
require(amount != 0, "Bet should be in an 'active' state");
bet.amount = 0;
// The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners
// are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256
// preimage is intractable), and house is unable to alter the "reveal" after
// placeBet have been mined (as Keccak256 collision finding is also intractable).
bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
transferCryptoTycoonsFee(amount);
uint payout = 0;
payout += processVIPBenefit(bet.gambler, amount);
payout += processRoulette(bet.gambler, bet.betMask, entropy, amount);
processJackpot(bet.gambler, entropy, amount);
processInviterBenefit(bet.gambler, amount);
bet.gambler.transfer(payout);
}
// Refund transaction - return the bet amount of a roll that was not processed in a due timeframe.
// Processing such blocks is not possible due to EVM limitations (see BET_EXPIRATION_BLOCKS comment above for details).
// In case you ever find yourself in a situation like this, just contact the {} support, however nothing precludes you from invoking this method yourself.
function refundBet(uint commit) external {
// Check that bet is in 'active' state.
Bet storage bet = bets[commit];
uint amount = bet.amount;
require(amount != 0, "Bet should be in an 'active' state");
// Check that bet has already expired.
require(block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
// Move bet into 'processed' state, release funds.
bet.amount = 0;
uint winAmount = getWinAmount(bet.betMask, amount);
lockedInBets -= uint128(winAmount);
// Send the refund.
bet.gambler.transfer(amount);
emit Refund(bet.gambler, amount);
}
// Funds withdrawal to cover costs of HalfRoulette operation.
function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner {
require(withdrawAmount <= address(this).balance, "Increase amount larger than balance.");
require(lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds.");
beneficiary.transfer(withdrawAmount); //injected SHORT ADDRESS ATTACK
}
} | assembly 1111 constant 11 11 | function getWinRate(uint betMask) public pure returns (uint rate) {
uint ODD_EVEN_RATE = 50000;
uint LEFT_RIGHT_RATE = 45833;
uint MIX_ODD_RATE = 25000;
uint MIX_EVEN_RATE = 20833;
uint EQUAL_RATE = 8333;
assembly {
switch betMask
}
}
| 897,334 | [
1,
28050,
16344,
21,
5381,
4648,
4648,
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,
13876,
267,
4727,
12,
11890,
2701,
5796,
13,
1071,
16618,
1135,
261,
11890,
4993,
13,
288,
203,
3639,
2254,
531,
5698,
67,
24427,
1157,
67,
24062,
273,
1381,
2787,
31,
203,
3639,
2254,
9686,
67,
11847,
67,
24062,
273,
1059,
8204,
3707,
31,
203,
3639,
2254,
490,
12507,
67,
1212,
40,
67,
24062,
273,
6969,
3784,
31,
203,
3639,
2254,
490,
12507,
67,
24427,
1157,
67,
24062,
273,
4200,
28,
3707,
31,
203,
3639,
2254,
18231,
67,
24062,
273,
1725,
3707,
23,
31,
203,
3639,
19931,
288,
203,
5411,
1620,
2701,
5796,
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
] |
./full_match/1/0xBcaDbCaBB69CCe22D134079969Eb08D3f644C2ce/sources/contracts/ThunderBot.sol | * @dev Sets the revenue share wallet address. Can only be called by the owner. @param _address Wallet address/ | function setRevShareWallet(address _address) public onlyOwner {
revShareWallet = _address;
}
| 4,862,011 | [
1,
2785,
326,
283,
24612,
7433,
9230,
1758,
18,
4480,
1338,
506,
2566,
635,
326,
3410,
18,
225,
389,
2867,
20126,
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
] | [
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,
444,
10070,
9535,
16936,
12,
2867,
389,
2867,
13,
1071,
1338,
5541,
288,
203,
3639,
5588,
9535,
16936,
273,
389,
2867,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-09-23
*/
// File: contracts/Dependencies/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
/*
* @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: contracts/proxy/Dependencies/Ownable.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 () internal {
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 {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/Dependencies/ReentrancyGuard.sol
/**
* @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: contracts/Dependencies/SafeMath.sol
/**
* @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: contracts/Dependencies/IERC20.sol
/**
* @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: contracts/Dependencies/Address.sol
/**
* @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: contracts/Dependencies/SafeERC20.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");
}
}
}
// File: contracts/Dependencies/IERC165.sol
/**
* @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: contracts/Dependencies/IERC1155.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;
}
// File: contracts/Dependencies/HasCopyright.sol
interface HasCopyright {
struct Copyright {
address author;
uint feeRateNumerator;
}
function getCopyright(uint tokenId) external returns (Copyright memory);
function getFeeRateDenominator() external returns (uint);
}
// File: contracts/proxy/FixedPriceTrade1155.sol
contract FixedPriceTrade1155 is Ownable, ReentrancyGuard {
using SafeMath for uint;
using SafeERC20 for IERC20;
uint private _orderIdCounter;
bool private _onlyInitOnce;
// Target ERC1155 address that involves with copyright
address private _ERC1155AddressWithCopyright;
struct Order {
// Address of maker
address maker;
// Address of ERC1155 token to sell
address tokenAddress;
// Id of ERC1155 token to sell
uint id;
// Remaining amount of ERC1155 token in this order
uint remainingAmount;
// Address of ERC20 token to pay
address payTokenAddress;
// Fixed price of ERC20 token to pay
uint fixedPrice;
// Whether the order is available
bool isAvailable;
}
// Mapping from order id to Order info
mapping(uint => Order) private _orders;
// Payment whitelist for the address of ERC20
mapping(address => bool) private _paymentWhitelist;
event PaymentWhitelistChange(address erc20Addr, bool jurisdiction);
event ERC1155AddressWithCopyrightChanged(address previousAddress, address currentAddress);
event MakeOrder(uint orderId, address maker, address tokenAddress, uint id, uint remainingAmount,
address payTokenAddress, uint fixedPrice);
event UpdateOrder(uint orderId, address operator, uint newRemainingAmount, address newPayTokenAddress,
uint newFixedPrice);
event TakeOrder(uint orderId, address taker, address maker, address tokenAddress, uint id, uint amount,
address payTokenAddress, uint fixedPrice);
event CancelOrder(uint orderId, address operator);
event PayCopyrightFee(uint orderId, address taker, address author, uint copyrightFee);
modifier onlyPaymentWhitelist(address erc20Addr) {
require(_paymentWhitelist[erc20Addr],
"the pay token address isn't in the whitelist");
_;
}
function init(address ERC1155AddressWithCopyright, address newOwner) public {
require(!_onlyInitOnce, "already initialized");
_ERC1155AddressWithCopyright = ERC1155AddressWithCopyright;
emit ERC1155AddressWithCopyrightChanged(address(0), ERC1155AddressWithCopyright);
_transferOwnership(newOwner);
_onlyInitOnce = true;
}
/**
* @dev External function to set order by anyone.
* @param tokenAddress address Address of ERC1155 token contract
* @param id uint Id of ERC1155 token to sell
* @param amount uint Amount of target ERC1155 token to sell
* @param payTokenAddress address ERC20 address of token for payment
* @param fixedPrice uint Fixed price of total ERC1155 token
*/
function ask(
address tokenAddress,
uint id,
uint amount,
address payTokenAddress,
uint fixedPrice
)
external
nonReentrant
onlyPaymentWhitelist(payTokenAddress)
{
// 1. check the validity of params
_checkOrderParams(msg.sender, tokenAddress, id, amount, fixedPrice);
// 2. build order
Order memory order = Order({
maker : msg.sender,
tokenAddress : tokenAddress,
id : id,
remainingAmount : amount,
payTokenAddress : payTokenAddress,
fixedPrice : fixedPrice,
isAvailable : true
});
// 3. store order
uint currentOrderId = _orderIdCounter;
_orderIdCounter = _orderIdCounter.add(1);
_orders[currentOrderId] = order;
emit MakeOrder(currentOrderId, order.maker, order.tokenAddress, order.id, order.remainingAmount,
order.payTokenAddress, order.fixedPrice);
}
/**
* @dev External function to update the existing order by its setter.
* @param newAmount uint New amount of target ERC1155 token to sell
* @param newPayTokenAddress address New ERC20 address of token for payment
* @param newFixedPrice uint New fixed price of each ERC1155 token
*/
function updateOrder(
uint orderId,
uint newAmount,
address newPayTokenAddress,
uint newFixedPrice
)
external
nonReentrant
onlyPaymentWhitelist(newPayTokenAddress)
{
Order memory order = getOrder(orderId);
require(
order.isAvailable,
"the order has been closed"
);
require(
order.maker == msg.sender,
"the order can only be updated by its setter"
);
// 2. check the validity of params to update
_checkOrderParams(msg.sender, order.tokenAddress, order.id, newAmount, newFixedPrice);
// 3. update order
_orders[orderId].remainingAmount = newAmount;
_orders[orderId].payTokenAddress = newPayTokenAddress;
_orders[orderId].fixedPrice = newFixedPrice;
emit UpdateOrder(orderId, msg.sender, newAmount, newPayTokenAddress, newFixedPrice);
}
/**
* @dev External function to cancel the existing order by its setter.
* @param orderId uint The target id of order to be cancelled
*/
function cancelOrder(uint orderId) external {
Order memory order = getOrder(orderId);
require(
order.isAvailable,
"the order has been closed"
);
require(
order.maker == msg.sender,
"the order can only be updated by its setter"
);
_orders[orderId].isAvailable = false;
emit CancelOrder(orderId, msg.sender);
}
/**
* @dev External function to bid the existing order by anyone who can afford it.
* @param orderId uint The target id of order to buy ERC1155 tokens
* @param amount uint The amount of the tokens in the order to buy
*/
function bid(uint orderId, uint amount) external nonReentrant {
Order memory order = getOrder(orderId);
require(
order.isAvailable,
"the order has been closed"
);
require(
order.maker != msg.sender,
"the maker can't bid for its own order"
);
require(
amount > 0,
"amount must be > 0"
);
require(
order.remainingAmount >= amount,
"insufficient remaining tokens in the order"
);
uint newRemainingAmount = order.remainingAmount.sub(amount);
_orders[orderId].remainingAmount = newRemainingAmount;
// Check && pay copyright fee
(uint transferAmount, uint copyrightFee,address author) = _getTransferAndCopyrightFeeAndAuthor(order, amount);
IERC20 tokenToPay = IERC20(order.payTokenAddress);
if (copyrightFee != 0) {
// Pay the copyright fee to author
tokenToPay.safeTransferFrom(msg.sender, author, copyrightFee);
emit PayCopyrightFee(orderId, msg.sender, author, copyrightFee);
}
// Trade
tokenToPay.safeTransferFrom(msg.sender, order.maker, transferAmount);
IERC1155(order.tokenAddress).safeTransferFrom(order.maker, msg.sender, order.id, amount, "");
if (newRemainingAmount == 0) {
// Close the order
_orders[orderId].isAvailable = false;
}
emit TakeOrder(orderId, msg.sender, order.maker, order.tokenAddress, order.id, amount, order.payTokenAddress,
order.fixedPrice);
}
/**
* @dev Public function to change target ERC1155 address that involves with copyright only by the owner.
* @param newERC1155AddressWithCopyright address Target address of ERC1155 contract with copyright
*/
function setERC1155AddressWithCopyright(address newERC1155AddressWithCopyright) public onlyOwner {
address previousAddress = _ERC1155AddressWithCopyright;
_ERC1155AddressWithCopyright = newERC1155AddressWithCopyright;
emit ERC1155AddressWithCopyrightChanged(previousAddress, newERC1155AddressWithCopyright);
}
/**
* @dev Public function to set the payment whitelist only by the owner.
* @param erc20Addr address Address of erc20 for paying
* @param jurisdiction bool In or out of the whitelist
*/
function setPaymentWhitelist(address erc20Addr, bool jurisdiction) public onlyOwner {
_paymentWhitelist[erc20Addr] = jurisdiction;
emit PaymentWhitelistChange(erc20Addr, jurisdiction);
}
/**
* @dev Public function to query whether the target erc20 address is in the payment whitelist.
* @param erc20Addr address Target address of erc20 to query about
*/
function getPaymentWhitelist(address erc20Addr) public view returns (bool){
return _paymentWhitelist[erc20Addr];
}
/**
* @dev Public function to get the target ERC1155 address involved with copyright.
*/
function getERC1155AddressWithCopyright() public view returns (address){
return _ERC1155AddressWithCopyright;
}
/**
* @dev Public function to query the order by order Id.
* @param orderId uint Target id of order to query about
*/
function getOrder(uint orderId) public view returns (Order memory order){
order = _orders[orderId];
require(order.maker != address(0), "the target order doesn't exist");
}
function _getTransferAndCopyrightFeeAndAuthor(
Order memory order,
uint amount
)
private
returns
(
uint transferAmount,
uint copyrightFee,
address author
)
{
transferAmount = order.fixedPrice.mul(amount);
if (order.tokenAddress != _ERC1155AddressWithCopyright) {
// not the official address of ERC1155 token
return (transferAmount, copyrightFee, author);
}
HasCopyright ERC1155WithCopyrightCached = HasCopyright(order.tokenAddress);
HasCopyright.Copyright memory copyright = ERC1155WithCopyrightCached.getCopyright(order.id);
uint feeRateDenominator = ERC1155WithCopyrightCached.getFeeRateDenominator();
if (copyright.author == address(0) || copyright.feeRateNumerator == 0 || copyright.feeRateNumerator > feeRateDenominator) {
// the official ERC1155 token has an invalid copyright info for copyright fee
return (transferAmount, copyrightFee, author);
}
author = copyright.author;
copyrightFee = transferAmount.mul(copyright.feeRateNumerator).div(feeRateDenominator);
transferAmount = transferAmount.sub(copyrightFee);
}
function _checkOrderParams(
address orderSetter,
address tokenAddress,
uint id,
uint amount,
uint fixedPrice
)
private
view
{
// check whether the order setter has the target tokens && approval
IERC1155 tokenAddressCached = IERC1155(tokenAddress);
require(
tokenAddressCached.balanceOf(orderSetter, id) >= amount,
"insufficient amount of ERC1155"
);
require(
tokenAddressCached.isApprovedForAll(orderSetter, address(this)),
"the contract hasn't been approved for ERC1155 transferring"
);
require(amount > 0, "the amount must be > 0");
require(fixedPrice > 0, "the fixed price must be > 0");
}
} | * @dev External function to set order by anyone. @param tokenAddress address Address of ERC1155 token contract @param id uint Id of ERC1155 token to sell @param amount uint Amount of target ERC1155 token to sell @param payTokenAddress address ERC20 address of token for payment @param fixedPrice uint Fixed price of total ERC1155 token/ 1. check the validity of params 2. build order | function ask(
address tokenAddress,
uint id,
uint amount,
address payTokenAddress,
uint fixedPrice
)
external
nonReentrant
onlyPaymentWhitelist(payTokenAddress)
{
_checkOrderParams(msg.sender, tokenAddress, id, amount, fixedPrice);
Order memory order = Order({
maker : msg.sender,
tokenAddress : tokenAddress,
id : id,
remainingAmount : amount,
payTokenAddress : payTokenAddress,
fixedPrice : fixedPrice,
isAvailable : true
});
_orderIdCounter = _orderIdCounter.add(1);
_orders[currentOrderId] = order;
emit MakeOrder(currentOrderId, order.maker, order.tokenAddress, order.id, order.remainingAmount,
order.payTokenAddress, order.fixedPrice);
}
| 15,272,385 | [
1,
6841,
445,
358,
444,
1353,
635,
1281,
476,
18,
225,
1147,
1887,
1758,
5267,
434,
4232,
39,
2499,
2539,
1147,
6835,
225,
612,
2254,
3124,
434,
4232,
39,
2499,
2539,
1147,
358,
357,
80,
225,
3844,
2254,
16811,
434,
1018,
4232,
39,
2499,
2539,
1147,
358,
357,
80,
225,
8843,
1345,
1887,
1758,
4232,
39,
3462,
1758,
434,
1147,
364,
5184,
225,
5499,
5147,
2254,
15038,
6205,
434,
2078,
4232,
39,
2499,
2539,
1147,
19,
404,
18,
866,
326,
13800,
434,
859,
576,
18,
1361,
1353,
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,
565,
445,
6827,
12,
203,
3639,
1758,
1147,
1887,
16,
203,
3639,
2254,
612,
16,
203,
3639,
2254,
3844,
16,
203,
3639,
1758,
8843,
1345,
1887,
16,
203,
3639,
2254,
5499,
5147,
203,
565,
262,
203,
565,
3903,
203,
565,
1661,
426,
8230,
970,
203,
565,
1338,
6032,
18927,
12,
10239,
1345,
1887,
13,
203,
565,
288,
203,
3639,
389,
1893,
2448,
1370,
12,
3576,
18,
15330,
16,
1147,
1887,
16,
612,
16,
3844,
16,
5499,
5147,
1769,
203,
203,
3639,
4347,
3778,
1353,
273,
4347,
12590,
203,
3639,
312,
6388,
294,
1234,
18,
15330,
16,
203,
3639,
1147,
1887,
294,
1147,
1887,
16,
203,
3639,
612,
294,
612,
16,
203,
3639,
4463,
6275,
294,
3844,
16,
203,
3639,
8843,
1345,
1887,
294,
8843,
1345,
1887,
16,
203,
3639,
5499,
5147,
294,
5499,
5147,
16,
203,
3639,
28293,
294,
638,
203,
3639,
15549,
203,
203,
3639,
389,
1019,
548,
4789,
273,
389,
1019,
548,
4789,
18,
1289,
12,
21,
1769,
203,
3639,
389,
9972,
63,
2972,
21303,
65,
273,
1353,
31,
203,
3639,
3626,
4344,
2448,
12,
2972,
21303,
16,
1353,
18,
29261,
16,
1353,
18,
2316,
1887,
16,
1353,
18,
350,
16,
1353,
18,
17956,
6275,
16,
203,
5411,
1353,
18,
10239,
1345,
1887,
16,
1353,
18,
12429,
5147,
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
] |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
/*
* @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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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);
}
/**
* @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;
}
}
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @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 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 {_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 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 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 {
require(
hasRole(getRoleAdmin(role), _msgSender()),
"AccessControl: sender must be an admin to grant"
);
_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 {
require(
hasRole(getRoleAdmin(role), _msgSender()),
"AccessControl: sender must be an admin to revoke"
);
_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 {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = 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());
}
}
}
interface IOndo {
enum InvestorType {CoinlistTranche1, CoinlistTranche2, SeedTranche}
// ----------- State changing api -----------
/// @notice Called by timelock contract to initialize locked balance of coinlist/seed investor
function updateTrancheBalance(
address beneficiary,
uint256 rawAmount,
InvestorType tranche
) external;
// ----------- Getters -----------
/// @notice Gets the TOTAL amount of Ondo available for an address
function getFreedBalance(address account) external view returns (uint96);
/// @notice Gets the initial locked balance and unlocked Ondo for an address
function getVestedBalance(address account)
external
view
returns (uint96, uint96);
}
abstract contract LinearTimelock {
struct InvestorParam {
IOndo.InvestorType investorType;
uint96 initialBalance;
}
/// @notice the timestamp at which releasing is allowed
uint256 public cliffTimestamp;
/// @notice the linear vesting period for the first tranche
uint256 public immutable tranche1VestingPeriod;
/// @notice the linear vesting period for the second tranche
uint256 public immutable tranche2VestingPeriod;
/// @notice the linear vesting period for the Seed/Series A Tranche
uint256 public immutable seedVestingPeriod;
/// @dev mapping of balances for each investor
mapping(address => InvestorParam) internal investorBalances;
/// @notice role that allows updating of tranche balances - granted to Merkle airdrop contract
bytes32 public constant TIMELOCK_UPDATE_ROLE =
keccak256("TIMELOCK_UPDATE_ROLE");
constructor(
uint256 _cliffTimestamp,
uint256 _tranche1VestingPeriod,
uint256 _tranche2VestingPeriod,
uint256 _seedVestingPeriod
) {
cliffTimestamp = _cliffTimestamp;
tranche1VestingPeriod = _tranche1VestingPeriod;
tranche2VestingPeriod = _tranche2VestingPeriod;
seedVestingPeriod = _seedVestingPeriod;
}
function passedCliff() public view returns (bool) {
return block.timestamp > cliffTimestamp;
}
/// @dev the seedVestingPeriod is the longest vesting period
function passedAllVestingPeriods() public view returns (bool) {
return block.timestamp > cliffTimestamp + seedVestingPeriod;
}
/**
@notice View function to get the user's initial balance and current amount of freed balance
*/
function getVestedBalance(address account)
external
view
returns (uint256, uint256)
{
if (investorBalances[account].initialBalance == 0) {
return (0, 0);
}
InvestorParam memory investorParam = investorBalances[account];
uint96 amountAvailable;
if (passedAllVestingPeriods()) {
amountAvailable = investorParam.initialBalance;
} else if (passedCliff()) {
(uint256 vestingPeriod, uint256 elapsed) =
_getTrancheInfo(investorParam.investorType);
amountAvailable = _proportionAvailable(
elapsed,
vestingPeriod,
investorParam
);
} else {
amountAvailable = 0;
}
return (investorParam.initialBalance, amountAvailable);
}
function _getTrancheInfo(IOndo.InvestorType investorType)
internal
view
returns (uint256 vestingPeriod, uint256 elapsed)
{
elapsed = block.timestamp - cliffTimestamp;
if (investorType == IOndo.InvestorType.CoinlistTranche1) {
elapsed = elapsed > tranche1VestingPeriod
? tranche1VestingPeriod
: elapsed;
vestingPeriod = tranche1VestingPeriod;
} else if (investorType == IOndo.InvestorType.CoinlistTranche2) {
elapsed = elapsed > tranche2VestingPeriod
? tranche2VestingPeriod
: elapsed;
vestingPeriod = tranche2VestingPeriod;
} else if (investorType == IOndo.InvestorType.SeedTranche) {
elapsed = elapsed > seedVestingPeriod ? seedVestingPeriod : elapsed;
vestingPeriod = seedVestingPeriod;
}
}
function _proportionAvailable(
uint256 elapsed,
uint256 vestingPeriod,
InvestorParam memory investorParam
) internal pure returns (uint96) {
if (investorParam.investorType == IOndo.InvestorType.SeedTranche) {
// Seed/Series A Tranche Balance = proportionAvail*2/3 + x/3, where x = Balance. This allows 1/3 of the series A balance to be unlocked at cliff
uint96 vestedAmount =
safe96(
(((investorParam.initialBalance * elapsed) / vestingPeriod) * 2) / 3,
"Ondo::_proportionAvailable: amount exceeds 96 bits"
);
return
add96(
vestedAmount,
investorParam.initialBalance / 3,
"Ondo::_proportionAvailable: overflow"
);
} else {
return
safe96(
(investorParam.initialBalance * elapsed) / vestingPeriod,
"Ondo::_proportionAvailable: amount exceeds 96 bits"
);
}
}
function safe32(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage)
internal
pure
returns (uint96)
{
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
}
contract Ondo is AccessControl, LinearTimelock {
/// @notice EIP-20 token name for this token
string public constant name = "Ondo";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "ONDO";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
// whether token transfers are allowed
bool public transferAllowed; // false by default
/// @notice Total number of tokens in circulation
uint256 public totalSupply = 10_000_000_000e18; // 10 billion Ondo
// Allowance amounts on behalf of others
mapping(address => mapping(address => uint96)) internal allowances;
// Official record of token balances for each account
mapping(address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping(address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH =
keccak256(
"EIP712Domain(string name,uint256 chainId,address verifyingContract)"
);
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The identifier of the role which allows special transfer privileges.
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(
address indexed delegate,
uint256 previousBalance,
uint256 newBalance
);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
event CliffTimestampUpdate(uint256 newTimestamp);
/**
* @dev Emitted when the transfer is enabled triggered by `account`.
*/
event TransferEnabled(address account);
/// @notice a modifier which checks if transfers are allowed
modifier whenTransferAllowed() {
require(
transferAllowed || hasRole(TRANSFER_ROLE, msg.sender),
"OndoToken: Transfers not allowed or not right privillege"
);
_;
}
/**
* @notice Construct a new Ondo token
* @param _governance The initial account to grant owner permission and all the tokens
*/
constructor(
address _governance,
uint256 _cliffTimestamp,
uint256 _tranche1VestingPeriod,
uint256 _tranche2VestingPeriod,
uint256 _seedVestingPeriod
)
LinearTimelock(
_cliffTimestamp,
_tranche1VestingPeriod,
_tranche2VestingPeriod,
_seedVestingPeriod
)
{
balances[_governance] = uint96(totalSupply);
_setupRole(DEFAULT_ADMIN_ROLE, _governance);
_setupRole(TRANSFER_ROLE, _governance);
_setupRole(MINTER_ROLE, _governance);
emit Transfer(address(0), _governance, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender)
external
view
returns (uint256)
{
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, "Ondo::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint256) {
return balances[account];
}
/**
* @notice Get the total number of UNLOCKED tokens held by the `account`
* @param account The address of the account to get the unlocked balance of
* @return The number of unlocked tokens held.
*/
function getFreedBalance(address account) external view returns (uint256) {
if (investorBalances[account].initialBalance > 0) {
return _getFreedBalance(account);
} else {
return balances[account];
}
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Ondo::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 rawAmount
) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Ondo::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != type(uint96).max) {
uint96 newAllowance =
sub96(
spenderAllowance,
amount,
"Ondo::transferFrom: transfer amount exceeds spender allowance"
);
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
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), "Ondo::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Ondo::delegateBySig: invalid nonce");
require(
block.timestamp <= expiry,
"Ondo::delegateBySig: signature expired"
);
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber)
public
view
returns (uint96)
{
require(
blockNumber < block.number,
"Ondo::getPriorVotes: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
/**
* @notice Create `rawAmount` new tokens and assign them to `account`.
* @param account The address to give newly minted tokens to
* @param rawAmount Number of new tokens to mint.
* @dev Even though total token supply is uint96, we use uint256 for the amount for consistency with other external interfaces.
*/
function mint(address account, uint256 rawAmount) external {
require(hasRole(MINTER_ROLE, msg.sender), "Ondo::mint: not authorized");
require(account != address(0), "cannot mint to the zero address");
uint96 amount = safe96(rawAmount, "Ondo::mint: amount exceeds 96 bits");
uint96 supply =
safe96(totalSupply, "Ondo::mint: totalSupply exceeds 96 bits");
totalSupply = add96(supply, amount, "Ondo::mint: token supply overflow");
balances[account] = add96(
balances[account],
amount,
"Ondo::mint: balance overflow"
);
emit Transfer(address(0), account, amount);
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(
address src,
address dst,
uint96 amount
) internal whenTransferAllowed {
require(
src != address(0),
"Ondo::_transferTokens: cannot transfer from the zero address"
);
require(
dst != address(0),
"Ondo::_transferTokens: cannot transfer to the zero address"
);
if (investorBalances[src].initialBalance > 0) {
require(
amount <= _getFreedBalance(src),
"Ondo::_transferTokens: not enough unlocked balance"
);
}
balances[src] = sub96(
balances[src],
amount,
"Ondo::_transferTokens: transfer amount exceeds balance"
);
balances[dst] = add96(
balances[dst],
amount,
"Ondo::_transferTokens: transfer amount overflows"
);
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld =
srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew =
sub96(srcRepOld, amount, "Ondo::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld =
dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew =
add96(dstRepOld, amount, "Ondo::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber =
safe32(
block.number,
"Ondo::_writeCheckpoint: block number exceeds 32 bits"
);
if (
nCheckpoints > 0 &&
checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber
) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
/**
* @notice Turn on _transferAllowed variable. Transfers are enabled
*/
function enableTransfer() external {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"Ondo::enableTransfer: not authorized"
);
transferAllowed = true;
emit TransferEnabled(msg.sender);
}
/**
* @notice Called by merkle airdrop contract to initialize locked balances
*/
function updateTrancheBalance(
address beneficiary,
uint256 rawAmount,
IOndo.InvestorType investorType
) external {
require(hasRole(TIMELOCK_UPDATE_ROLE, msg.sender));
require(rawAmount > 0, "Ondo::updateTrancheBalance: amount must be > 0");
require(
investorBalances[beneficiary].initialBalance == 0,
"Ondo::updateTrancheBalance: already has timelocked Ondo"
); //Prevents users from being in more than 1 tranche
uint96 amount =
safe96(rawAmount, "Ondo::updateTrancheBalance: amount exceeds 96 bits");
investorBalances[beneficiary] = InvestorParam(investorType, amount);
}
/**
* @notice Internal function the amount of unlocked Ondo for an account that participated in Coinlist/Seed Investments
*/
function _getFreedBalance(address account) internal view returns (uint96) {
if (passedAllVestingPeriods()) {
//all vesting periods are over, just return the total balance
return balances[account];
} else {
InvestorParam memory investorParam = investorBalances[account];
if (passedCliff()) {
//we are in between the cliff timestamp and last vesting period
(uint256 vestingPeriod, uint256 elapsed) =
_getTrancheInfo(investorParam.investorType);
uint96 lockedBalance =
sub96(
investorParam.initialBalance,
_proportionAvailable(elapsed, vestingPeriod, investorParam),
"Ondo::getFreedBalance: locked balance underflow"
);
return
sub96(
balances[account],
lockedBalance,
"Ondo::getFreedBalance: total freed balance underflow"
);
} else {
//we have not hit the cliff yet, all investor balance is locked
return
sub96(
balances[account],
investorParam.initialBalance,
"Ondo::getFreedBalance: balance underflow"
);
}
}
}
function updateCliffTimestamp(uint256 newTimestamp) external {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"Ondo::updateCliffTimestamp: not authorized"
);
cliffTimestamp = newTimestamp;
emit CliffTimestampUpdate(newTimestamp);
}
} | * @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 {
require(
hasRole(getRoleAdmin(role), _msgSender()),
"AccessControl: sender must be an admin to revoke"
);
_revokeRole(role, account);
}
| 1,554,247 | [
1,
10070,
601,
281,
1375,
4615,
68,
628,
1375,
4631,
8338,
971,
1375,
4631,
68,
9323,
2118,
17578,
1375,
4615,
9191,
24169,
279,
288,
2996,
10070,
14276,
97,
871,
18,
29076,
30,
300,
326,
4894,
1297,
1240,
12176,
4615,
10335,
11,
87,
3981,
2478,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
18007,
2996,
12,
3890,
1578,
2478,
16,
1758,
2236,
13,
1071,
5024,
3849,
288,
203,
565,
2583,
12,
203,
1377,
28335,
12,
588,
2996,
4446,
12,
4615,
3631,
389,
3576,
12021,
1435,
3631,
203,
1377,
315,
16541,
30,
5793,
1297,
506,
392,
3981,
358,
18007,
6,
203,
565,
11272,
203,
203,
565,
389,
9083,
3056,
2996,
12,
4615,
16,
2236,
1769,
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
] |
// File: node_modules\@openzeppelin\contracts\introspection\IERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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\ERC1155\IERC1155.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.6.2;
/**
* @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;
}
// File: @openzeppelin\contracts\token\ERC1155\IERC1155Receiver.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
/**
* _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);
}
// File: node_modules\eth-item-token-standard\IERC1155Views.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title IERC1155Views - An optional utility interface to improve the ERC-1155 Standard.
* @dev This interface introduces some additional capabilities for ERC-1155 Tokens.
*/
interface IERC1155Views {
/**
* @dev Returns the total supply of the given token id
* @param objectId the id of the token whose availability you want to know
*/
function totalSupply(uint256 objectId) external view returns (uint256);
/**
* @dev Returns the name of the given token id
* @param objectId the id of the token whose name you want to know
*/
function name(uint256 objectId) external view returns (string memory);
/**
* @dev Returns the symbol of the given token id
* @param objectId the id of the token whose symbol you want to know
*/
function symbol(uint256 objectId) external view returns (string memory);
/**
* @dev Returns the decimals of the given token id
* @param objectId the id of the token whose decimals you want to know
*/
function decimals(uint256 objectId) external view returns (uint256);
/**
* @dev Returns the uri of the given token id
* @param objectId the id of the token whose uri you want to know
*/
function uri(uint256 objectId) external view returns (string memory);
}
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.6.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: node_modules\eth-item-token-standard\IBaseTokenData.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
interface IBaseTokenData {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
// File: node_modules\eth-item-token-standard\IERC20Data.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
interface IERC20Data is IBaseTokenData {
function decimals() external view returns (uint256);
}
// File: node_modules\eth-item-token-standard\IERC20NFTWrapper.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
interface IERC20NFTWrapper is IERC20, IERC20Data {
function init(uint256 objectId, string memory name, string memory symbol, uint256 decimals) external;
function mainWrapper() external view returns (address);
function objectId() external view returns (uint256);
function mint(address owner, uint256 amount) external;
function burn(address owner, uint256 amount) external;
}
// File: eth-item-token-standard\IEthItem.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
interface IEthItem is IERC1155, IERC1155Views, IBaseTokenData {
function init(
address eRC20NFTWrapperModel,
string calldata name,
string calldata symbol
) external;
function toERC20WrapperAmount(uint256 objectId, uint256 ethItemAmount) external view returns (uint256 erc20WrapperAmount);
function toEthItemAmount(uint256 objectId, uint256 erc20WrapperAmount) external view returns (uint256 ethItemAmount);
function erc20NFTWrapperModel() external view returns (address);
function asERC20(uint256 objectId) external view returns (IERC20NFTWrapper);
function emitTransferSingleEvent(address sender, address from, address to, uint256 objectId, uint256 amount) external;
function mint(uint256 amount, string calldata partialUri)
external
returns (uint256, address);
function burn(
uint256 objectId,
uint256 amount
) external;
function burnBatch(
uint256[] calldata objectIds,
uint256[] calldata amounts
) external;
event Mint(uint256 objectId, address tokenAddress, uint256 amount);
}
// File: models\common\IEthItemModelBase.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev This interface contains the commonn data provided by all the EthItem models
*/
interface IEthItemModelBase is IEthItem {
/**
* @dev Contract Initialization, the caller of this method should be a Contract containing the logic to provide the EthItemERC20WrapperModel to be used to create ERC20-based objectIds
* @param name the chosen name for this NFT
* @param symbol the chosen symbol (Ticker) for this NFT
*/
function init(string calldata name, string calldata symbol) external;
/**
* @return modelVersionNumber The version number of the Model, it should be progressive
*/
function modelVersion() external pure returns(uint256 modelVersionNumber);
/**
* @return factoryAddress the address of the Contract which initialized this EthItem
*/
function factory() external view returns(address factoryAddress);
}
// File: models\ERC1155\1\IERC1155V1.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev EthItem token standard - Version 1
* This is a pure extension of the EthItem Token Standard, which also introduces an optional extension that can introduce some external behavior to the EthItem.
* Extension can also be a simple wallet
*/
interface IERC1155V1 is IEthItemModelBase {
/**
* @dev Contract initialization
* @param name the chosen name for this NFT
* @param symbol the chosen symbol (Ticker) for this NFT
* @param extensionAddress the optional address of the extension. It can be a Wallet or a SmartContract
* @param extensionInitPayload the optional payload useful to call the extension within the new created EthItem
*/
function init(string calldata name, string calldata symbol, address extensionAddress, bytes calldata extensionInitPayload) external returns(bytes memory extensionInitCallResponse);
/**
* @return extensionAddress the address of the eventual EthItem main owner or the SmartContract which contains all the logics to directly exploit all the Collection Items of this EthItem. It can also be a simple wallet
*/
function extension() external view returns (address extensionAddress);
/**
* @param operator The address to know info about
* @return result true if the given address is able to mint new tokens, false otherwise.
*/
function canMint(address operator) external view returns (bool result);
/**
* @dev Method callable by the extension only and useful to release the control on the EthItem, which from now on will run independently
*/
function releaseExtension(bool keepMint) external;
}
// File: @openzeppelin\contracts\GSN\Context.sol
// SPDX_License_Identifier: MIT
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\math\SafeMath.sol
// SPDX_License_Identifier: MIT
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
// SPDX_License_Identifier: MIT
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) {
// This method relies in 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");
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\introspection\ERC165.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: eth-item-token-standard\EthItem.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title EthItem - An improved ERC1155 token with ERC20 trading capabilities.
* @dev In the EthItem standard, there is no a centralized storage where to save every objectId info.
* In fact every NFT data is saved in a specific ERC20 token that can also work as a standalone one, and let transfer parts of an atomic object.
* The ERC20 represents a unique Token Id, and its supply represents the entire supply of that Token Id.
* You can instantiate a EthItem as a brand-new one, or as a wrapper for pre-existent classic ERC1155 NFT.
* In the first case, you can introduce some particular permissions to mint new tokens.
* In the second case, you need to send your NFTs to the Wrapped EthItem (using the classic safeTransferFrom or safeBatchTransferFrom methods)
* and it will create a brand new ERC20 Token or mint new supply (in the case some tokens with the same id were transfered before yours).
*/
contract EthItem is IEthItem, Context, ERC165 {
using SafeMath for uint256;
using Address for address;
bytes4 internal constant _INTERFACEobjectId_ERC1155 = 0xd9b67a26;
string internal _name;
string internal _symbol;
mapping(uint256 => string) internal _objectUris;
mapping(uint256 => address) internal _dest;
mapping(address => bool) internal _isMine;
mapping(address => mapping(address => bool)) internal _operatorApprovals;
address internal _erc20NFTWrapperModel;
uint256 internal _decimals;
/**
* @dev Constructor
* When you create a EthItem, you can specify if you want to create a brand new one, passing the classic data like name, symbol, amd URI,
* or wrap a pre-existent ERC1155 NFT, passing its contract address.
* You can use just one of the two modes at the same time.
* In both cases, a ERC20 token address is mandatory. It will be used as a model to be cloned for every minted NFT.
* @param erc20NFTWrapperModel the address of the ERC20 pre-deployed model. I will not be used in the procedure, but just cloned as a brand-new one every time a new NFT is minted.
* @param name the name of the brand new EthItem to be created. If you are wrapping a pre-existing ERC1155 NFT, this must be blank.
* @param symbol the symbol of the brand new EthItem to be created. If you are wrapping a pre-existing ERC1155 NFT, this must be blank.
*/
constructor(
address erc20NFTWrapperModel,
string memory name,
string memory symbol
) public {
if(erc20NFTWrapperModel != address(0)) {
init(erc20NFTWrapperModel, name, symbol);
}
}
/**
* @dev Utility method which contains the logic of the constructor.
* This is a useful trick to instantiate a contract when it is cloned.
*/
function init(
address erc20NFTWrapperModel,
string memory name,
string memory symbol
) public virtual override {
require(
_erc20NFTWrapperModel == address(0),
"Init already called!"
);
require(
erc20NFTWrapperModel != address(0),
"Model should be a valid ethereum address"
);
_erc20NFTWrapperModel = erc20NFTWrapperModel;
require(
keccak256(bytes(name)) != keccak256(""),
"Name is mandatory"
);
require(
keccak256(bytes(symbol)) != keccak256(""),
"Symbol is mandatory"
);
_name = name;
_symbol = symbol;
_decimals = 18;
_registerInterface(this.safeBatchTransferFrom.selector);
_registerInterface(_INTERFACEobjectId_ERC1155);
_registerInterface(this.balanceOf.selector);
_registerInterface(this.balanceOfBatch.selector);
_registerInterface(this.setApprovalForAll.selector);
_registerInterface(this.isApprovedForAll.selector);
_registerInterface(this.safeTransferFrom.selector);
_registerInterface(this.uri.selector);
_registerInterface(this.totalSupply.selector);
_registerInterface(0x00ad800c); //name(uint256)
_registerInterface(0x4e41a1fb); //symbol(uint256)
_registerInterface(this.decimals.selector);
_registerInterface(0x06fdde03); //name()
_registerInterface(0x95d89b41); //symbol()
}
/**
* @dev Mint
* If the EthItem does not wrap a pre-existent NFT, this call is used to mint new NFTs, according to the permission rules provided by the Token creator.
* @param amount The amount of tokens to be created. It must be greater than 1 unity.
* @param objectUri The Uri to locate this new token's metadata.
*/
function mint(uint256 amount, string memory objectUri)
public
virtual
override
returns (uint256 objectId, address tokenAddress)
{
require(
amount > 1,
"You need to pass more than a token"
);
require(
keccak256(bytes(objectUri)) != keccak256(""),
"Uri cannot be empty"
);
(objectId, tokenAddress) = _mint(msg.sender, amount);
_objectUris[objectId] = objectUri;
}
/**
* @dev Burn
* You can choose to burn your NFTs.
* In case this Token wraps a pre-existent ERC1155 NFT, you will receive the wrapped NFTs.
*/
function burn(
uint256 objectId,
uint256 amount
) public virtual override {
uint256[] memory objectIds = new uint256[](1);
objectIds[0] = objectId;
uint256[] memory amounts = new uint256[](1);
amounts[0] = amount;
_burn(msg.sender, objectIds, amounts);
emit TransferSingle(msg.sender, msg.sender, address(0), objectId, amount);
}
/**
* @dev Burn Batch
* Same as burn, but for multiple NFTs at the same time
*/
function burnBatch(
uint256[] memory objectIds,
uint256[] memory amounts
) public virtual override {
_burn(msg.sender, objectIds, amounts);
emit TransferBatch(msg.sender, msg.sender, address(0), objectIds, amounts);
}
function _burn(address owner,
uint256[] memory objectIds,
uint256[] memory amounts) internal virtual {
for (uint256 i = 0; i < objectIds.length; i++) {
asERC20(objectIds[i]).burn(
owner,
toERC20WrapperAmount(objectIds[i], amounts[i])
);
}
}
/**
* @dev get the address of the ERC20 Contract used as a model
*/
function erc20NFTWrapperModel() public virtual override view returns (address) {
return _erc20NFTWrapperModel;
}
/**
* @dev Gives back the address of the ERC20 Token representing this Token Id
*/
function asERC20(uint256 objectId)
public
virtual
override
view
returns (IERC20NFTWrapper)
{
return IERC20NFTWrapper(_dest[objectId]);
}
/**
* @dev Returns the total supply of the given token id
* @param objectId the id of the token whose availability you want to know
*/
function totalSupply(uint256 objectId)
public
virtual
override
view
returns (uint256)
{
return toEthItemAmount(objectId, asERC20(objectId).totalSupply());
}
/**
* @dev Returns the name of the given token id
* @param objectId the id of the token whose name you want to know
*/
function name(uint256 objectId)
public
virtual
override
view
returns (string memory)
{
return asERC20(objectId).name();
}
function name() public virtual override view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the given token id
* @param objectId the id of the token whose symbol you want to know
*/
function symbol(uint256 objectId)
public
virtual
override
view
returns (string memory)
{
return asERC20(objectId).symbol();
}
function symbol() public virtual override view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the decimals of the given token id
*/
function decimals(uint256)
public
virtual
override
view
returns (uint256)
{
return 1;
}
/**
* @dev Returns the uri of the given token id
* @param objectId the id of the token whose uri you want to know
*/
function uri(uint256 objectId)
public
virtual
override
view
returns (string memory)
{
return _objectUris[objectId];
}
/**
* @dev Classic ERC1155 Standard Method
*/
function balanceOf(address account, uint256 objectId)
public
virtual
override
view
returns (uint256)
{
return toEthItemAmount(objectId, asERC20(objectId).balanceOf(account));
}
/**
* @dev Classic ERC1155 Standard Method
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory objectIds
) public virtual override view returns (uint256[] memory balances) {
balances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; i++) {
balances[i] = balanceOf(accounts[i], objectIds[i]);
}
}
/**
* @dev Classic ERC1155 Standard Method
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
address sender = _msgSender();
require(
sender != operator,
"ERC1155: setting approval status for self"
);
_operatorApprovals[sender][operator] = approved;
emit ApprovalForAll(sender, operator, approved);
}
/**
* @dev Classic ERC1155 Standard Method
*/
function isApprovedForAll(address account, address operator)
public
virtual
override
view
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev Classic ERC1155 Standard Method
*/
function safeTransferFrom(
address from,
address to,
uint256 objectId,
uint256 amount,
bytes memory data
) public virtual override {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
require(
from == operator || isApprovedForAll(from, operator),
"ERC1155: caller is not owner nor approved"
);
asERC20(objectId).transferFrom(from, to, toERC20WrapperAmount(objectId, amount));
emit TransferSingle(operator, from, to, objectId, amount);
_doSafeTransferAcceptanceCheck(
operator,
from,
to,
objectId,
amount,
data
);
}
/**
* @dev Classic ERC1155 Standard Method
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory objectIds,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
for (uint256 i = 0; i < objectIds.length; i++) {
asERC20(objectIds[i]).transferFrom(
from,
to,
toERC20WrapperAmount(objectIds[i], amounts[i])
);
}
address operator = _msgSender();
emit TransferBatch(operator, from, to, objectIds, amounts);
_doSafeBatchTransferAcceptanceCheck(
operator,
from,
to,
objectIds,
amounts,
data
);
}
function emitTransferSingleEvent(address sender, address from, address to, uint256 objectId, uint256 amount) public override {
require(_dest[objectId] == msg.sender, "Unauthorized Action!");
uint256 entireAmount = toEthItemAmount(objectId, amount);
if(entireAmount == 0) {
return;
}
emit TransferSingle(sender, from, to, objectId, entireAmount);
}
function toERC20WrapperAmount(uint256 objectId, uint256 ethItemAmount) public override virtual view returns (uint256 erc20WrapperAmount) {
erc20WrapperAmount = ethItemAmount * (10**asERC20(objectId).decimals());
}
function toEthItemAmount(uint256 objectId, uint256 erc20WrapperAmount) public override virtual view returns (uint256 ethItemAmount) {
ethItemAmount = erc20WrapperAmount / (10**asERC20(objectId).decimals());
}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155Received(
operator,
from,
id,
amount,
data
)
returns (bytes4 response) {
if (
response != IERC1155Receiver(to).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
) internal virtual {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155BatchReceived(
operator,
from,
ids,
amounts,
data
)
returns (bytes4 response) {
if (
response !=
IERC1155Receiver(to).onERC1155BatchReceived.selector
) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _clone(address original) internal returns (address copy) {
assembly {
mstore(
0,
or(
0x5880730000000000000000000000000000000000000000803b80938091923cF3,
mul(original, 0x1000000000000000000)
)
)
copy := create(0, 0, 32)
switch extcodesize(copy)
case 0 {
invalid()
}
}
}
function _mint(
address from,
uint256 amount
) internal virtual returns (uint256 objectId, address wrapperAddress) {
IERC20NFTWrapper wrapper = IERC20NFTWrapper(wrapperAddress = _clone(erc20NFTWrapperModel()));
_isMine[_dest[objectId = uint256(wrapperAddress)] = wrapperAddress] = true;
wrapper.init(objectId, _name, _symbol, _decimals);
wrapper.mint(from, amount * (10**_decimals));
emit Mint(objectId, wrapperAddress, amount);
emit TransferSingle(address(this), address(0), from, objectId, amount);
}
}
// File: orchestrator\IEthItemOrchestratorDependantElement.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
interface IEthItemOrchestratorDependantElement is IERC165 {
/**
* @dev GET - The DoubleProxy of the DFO linked to this Contract
*/
function doubleProxy() external view returns (address);
/**
* @dev SET - The DoubleProxy of the DFO linked to this Contract
* It can be done only by the Factory controller
* @param newDoubleProxy the new DoubleProxy address
*/
function setDoubleProxy(address newDoubleProxy) external;
function isAuthorizedOrchestrator(address operator) external view returns(bool);
}
// File: factory\IEthItemFactory.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title IEthItemFactory
* @dev This contract represents the Factory Used to deploy all the EthItems, keeping track of them.
*/
interface IEthItemFactory is IEthItemOrchestratorDependantElement {
/**
* @dev GET - The address of the Smart Contract whose code will serve as a model for all the EthItemERC20Wrappers (please see the eth-item-token-standard for further information).
*/
function ethItemERC20WrapperModel() external view returns (address ethItemERC20WrapperModelAddress);
/**
* @dev SET - The address of the Smart Contract whose code will serve as a model for all the EthItemERC20Wrappers (please see the eth-item-token-standard for further information).
* It can be done only by the Factory controller
*/
function setEthItemERC20WrapperModel(address ethItemERC20WrapperModelAddress) external;
/**
* @dev GET - The address of the Smart Contract whose code will serve as a model for all the ERC1155 NFT-Based EthItems.
* Every EthItem will have its own address, but the code will be cloned from this one.
*/
function erc1155Model() external view returns (address erc1155ModelAddress, uint256 erc1155ModelVersion);
/**
* @dev SET - The address of the ERC1155 NFT-Based EthItem model.
* It can be done only by the Factory controller
*/
function setERC1155Model(address erc1155ModelAddress) external;
/**
* @dev GET - The address of the Smart Contract whose code will serve as a model for all the Wrapped ERC1155 EthItems.
* Every EthItem will have its own address, but the code will be cloned from this one.
*/
function erc1155WrapperModel() external view returns (address erc1155WrapperModelAddress, uint256 erc1155WrapperModelVersion);
/**
* @dev SET - The address of the ERC1155 NFT-Based EthItem model.
* It can be done only by the Factory controller
*/
function setERC1155WrapperModel(address erc1155WrapperModelAddress) external;
/**
* @dev GET - The address of the Smart Contract whose code will serve as a model for all the Wrapped ERC20 EthItems.
*/
function erc20WrapperModel() external view returns (address erc20WrapperModelAddress, uint256 erc20WrapperModelVersion);
/**
* @dev SET - The address of the Smart Contract whose code will serve as a model for all the Wrapped ERC20 EthItems.
* It can be done only by the Factory controller
*/
function setERC20WrapperModel(address erc20WrapperModelAddress) external;
/**
* @dev GET - The address of the Smart Contract whose code will serve as a model for all the Wrapped ERC721 EthItems.
*/
function erc721WrapperModel() external view returns (address erc721WrapperModelAddress, uint256 erc721WrapperModelVersion);
/**
* @dev SET - The address of the Smart Contract whose code will serve as a model for all the Wrapped ERC721 EthItems.
* It can be done only by the Factory controller
*/
function setERC721WrapperModel(address erc721WrapperModelAddress) external;
/**
* @dev GET - The elements (numerator and denominator) useful to calculate the percentage fee to be transfered to the DFO for every new Minted EthItem
*/
function mintFeePercentage() external view returns (uint256 mintFeePercentageNumerator, uint256 mintFeePercentageDenominator);
/**
* @dev SET - The element useful to calculate the Percentage fee
* It can be done only by the Factory controller
*/
function setMintFeePercentage(uint256 mintFeePercentageNumerator, uint256 mintFeePercentageDenominator) external;
/**
* @dev Useful utility method to calculate the percentage fee to transfer to the DFO for the minted EthItem amount.
* @param erc20WrapperAmount The amount of minted EthItem
*/
function calculateMintFee(uint256 erc20WrapperAmount) external view returns (uint256 mintFee, address dfoWalletAddress);
/**
* @dev GET - The elements (numerator and denominator) useful to calculate the percentage fee to be transfered to the DFO for every Burned EthItem
*/
function burnFeePercentage() external view returns (uint256 burnFeePercentageNumerator, uint256 burnFeePercentageDenominator);
/**
* @dev SET - The element useful to calculate the Percentage fee
* It can be done only by the Factory controller
*/
function setBurnFeePercentage(uint256 burnFeePercentageNumerator, uint256 burnFeePercentageDenominator) external;
/**
* @dev Useful utility method to calculate the percentage fee to transfer to the DFO for the burned EthItem amount.
* @param erc20WrapperAmount The amount of burned EthItem
*/
function calculateBurnFee(uint256 erc20WrapperAmount) external view returns (uint256 burnFee, address dfoWalletAddress);
/**
* @dev Business Logic to create a brand-new EthItem.
* It raises the 'NewERC1155Created' event.
* @param modelInitCallPayload The ABI-encoded input parameters to be passed to the model to phisically create the NFT.
* It changes according to the Model Version.
* @param ethItemAddress The address of the new EthItem
* @param ethItemInitResponse The ABI-encoded output response eventually received by the Model initialization procedure.
*/
function createERC1155(bytes calldata modelInitCallPayload) external returns (address ethItemAddress, bytes memory ethItemInitResponse);
event NewERC1155Created(address indexed model, uint256 indexed modelVersion, address indexed tokenCreated, address creator);
/**
* @dev Business Logic to wrap already existing ERC1155 Tokens to obtain a new NFT-Based EthItem.
* It raises the 'NewWrappedERC1155Created' event.
* @param modelInitCallPayload The ABI-encoded input parameters to be passed to the model to phisically create the NFT.
* It changes according to the Model Version.
* @param ethItemAddress The address of the new EthItem
* @param ethItemInitResponse The ABI-encoded output response eventually received by the Model initialization procedure.
*/
function createWrappedERC1155(bytes calldata modelInitCallPayload) external returns (address ethItemAddress, bytes memory ethItemInitResponse);
event NewWrappedERC1155Created(address indexed model, uint256 indexed modelVersion, address indexed tokenCreated, address creator);
/**
* @dev Business Logic to wrap already existing ERC20 Tokens to obtain a new NFT-Based EthItem.
* It raises the 'NewWrappedERC20Created' event.
* @param modelInitCallPayload The ABI-encoded input parameters to be passed to the model to phisically create the NFT.
* It changes according to the Model Version.
* @param ethItemAddress The address of the new EthItem
* @param ethItemInitResponse The ABI-encoded output response eventually received by the Model initialization procedure.
*/
function createWrappedERC20(bytes calldata modelInitCallPayload) external returns (address ethItemAddress, bytes memory ethItemInitResponse);
event NewWrappedERC20Created(address indexed model, uint256 indexed modelVersion, address indexed tokenCreated, address creator);
/**
* @dev Business Logic to wrap already existing ERC721 Tokens to obtain a new NFT-Based EthItem.
* It raises the 'NewWrappedERC721Created' event.
* @param modelInitCallPayload The ABI-encoded input parameters to be passed to the model to phisically create the NFT.
* It changes according to the Model Version.
* @param ethItemAddress The address of the new EthItem
* @param ethItemInitResponse The ABI-encoded output response eventually received by the Model initialization procedure.
*/
function createWrappedERC721(bytes calldata modelInitCallPayload) external returns (address ethItemAddress, bytes memory ethItemInitResponse);
event NewWrappedERC721Created(address indexed model, uint256 indexed modelVersion, address indexed tokenCreated, address creator);
}
// File: models\common\EthItemModelBase.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
abstract contract EthItemModelBase is IEthItemModelBase, EthItem(address(0), "", "") {
address internal _factoryAddress;
function init(
address,
string memory,
string memory
) public virtual override(IEthItem, EthItem) {
revert("Cannot directly call this method.");
}
function init(
string memory name,
string memory symbol
) public override virtual {
require(_factoryAddress == address(0), "Init already called!");
super.init(IEthItemFactory(_factoryAddress = msg.sender).ethItemERC20WrapperModel(), name, symbol);
}
function modelVersion() public override virtual pure returns(uint256) {
return 1;
}
function factory() public override view returns (address) {
return _factoryAddress;
}
function _sendMintFeeToDFO(address from, uint256 objectId, uint256 erc20WrapperAmount) internal virtual returns(uint256 mintFeeToDFO) {
address dfoWallet;
(mintFeeToDFO, dfoWallet) = IEthItemFactory(_factoryAddress).calculateMintFee(erc20WrapperAmount);
if(mintFeeToDFO > 0 && dfoWallet != address(0)) {
asERC20(objectId).transferFrom(from, dfoWallet, mintFeeToDFO);
}
}
function _sendBurnFeeToDFO(address from, uint256 objectId, uint256 erc20WrapperAmount) internal virtual returns(uint256 burnFeeToDFO) {
address dfoWallet;
(burnFeeToDFO, dfoWallet) = IEthItemFactory(_factoryAddress).calculateBurnFee(erc20WrapperAmount);
if(burnFeeToDFO > 0 && dfoWallet != address(0)) {
asERC20(objectId).transferFrom(from, dfoWallet, burnFeeToDFO);
}
}
function safeTransferFrom(
address from,
address to,
uint256 objectId,
uint256 amount,
bytes memory data
) public virtual override(IERC1155, EthItem) {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
require(
from == operator || isApprovedForAll(from, operator),
"ERC1155: caller is not owner nor approved"
);
_doERC20Transfer(from, to, objectId, amount);
emit TransferSingle(operator, from, to, objectId, amount);
_doSafeTransferAcceptanceCheck(
operator,
from,
to,
objectId,
amount,
data
);
}
/**
* @dev Classic ERC1155 Standard Method
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory objectIds,
uint256[] memory amounts,
bytes memory data
) public virtual override(IERC1155, EthItem) {
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
for (uint256 i = 0; i < objectIds.length; i++) {
_doERC20Transfer(from, to, objectIds[i], amounts[i]);
}
address operator = _msgSender();
emit TransferBatch(operator, from, to, objectIds, amounts);
_doSafeBatchTransferAcceptanceCheck(
operator,
from,
to,
objectIds,
amounts,
data
);
}
function _doERC20Transfer(address from, address to, uint256 objectId, uint256 amount) internal virtual {
(,uint256 result) = _getCorrectERC20ValueForTransferOrBurn(from, objectId, amount);
asERC20(objectId).transferFrom(from, to, result);
}
function _getCorrectERC20ValueForTransferOrBurn(address from, uint256 objectId, uint256 amount) internal virtual view returns(uint256 balanceOfNormal, uint256 result) {
uint256 toTransfer = toERC20WrapperAmount(objectId, amount);
uint256 balanceOfDecimals = asERC20(objectId).balanceOf(from);
balanceOfNormal = balanceOf(from, objectId);
result = amount == balanceOfNormal ? balanceOfDecimals : toTransfer;
}
function _burn(
uint256 objectId,
uint256 amount
) internal virtual returns(uint256 burnt) {
(uint256 balanceOfNormal, uint256 result) = _getCorrectERC20ValueForTransferOrBurn(msg.sender, objectId, amount);
require(balanceOfNormal >= amount, "Insufficient Amount");
uint256 burnFeeToDFO = _sendBurnFeeToDFO(msg.sender, objectId, result);
asERC20(objectId).burn(msg.sender, burnt = result - burnFeeToDFO);
}
}
// File: models\ERC1155\1\ERC1155V1.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.6.0;
contract ERC1155V1 is IERC1155V1, EthItemModelBase {
address internal _extensionAddress;
bool internal _keepMint;
function init(string memory name, string memory symbol, address extensionAddress, bytes memory extensionInitPayload) public override virtual returns(bytes memory extensionInitCallResponse) {
super.init(name, symbol);
extensionInitCallResponse = _initExtension(extensionAddress, extensionInitPayload);
_keepMint = _extensionAddress == address(0);
}
function _initExtension(address extensionAddress, bytes memory extensionInitPayload) internal virtual returns(bytes memory extensionInitCallResponse) {
_extensionAddress = extensionAddress;
if (
extensionAddress != address(0) &&
keccak256(extensionInitPayload) != keccak256("")
) {
bool extensionInitCallResult = false;
(
extensionInitCallResult,
extensionInitCallResponse
) = extensionAddress.call(extensionInitPayload);
require(
extensionInitCallResult,
"Extension Init Call Result failed!"
);
}
}
function extension() public view virtual override returns (address) {
return _extensionAddress;
}
function canMint(address operator) public view virtual override returns (bool result) {
result = operator == _extensionAddress || (_extensionAddress == address(0) && _keepMint);
}
function balanceOf(address account, uint256 objectId)
public
virtual
override
view
returns (uint256)
{
(bool unique, uint256 unity,, uint256 erc20Decimals) = _isUnique(objectId);
uint256 accountBalance = asERC20(objectId).balanceOf(account);
if(unique) {
uint256 max = (unity * 51) / 100;
return accountBalance > max ? 1 : 0;
}
return (accountBalance / (10**erc20Decimals));
}
function mint(uint256 amount, string memory objectUri)
public
virtual
override
returns (uint256 objectId, address tokenAddress)
{
require(canMint(msg.sender), "Unauthorized action!");
require(
keccak256(bytes(objectUri)) != keccak256(""),
"Uri cannot be empty"
);
(objectId, tokenAddress) = _mint(msg.sender, amount);
_objectUris[objectId] = objectUri;
_sendMintFeeToDFO(msg.sender, objectId, toERC20WrapperAmount(objectId, amount));
}
function burn(
uint256 objectId,
uint256 amount
) public virtual override {
_burn(objectId, amount);
emit TransferSingle(msg.sender, msg.sender, address(0), objectId, amount);
}
function burnBatch(
uint256[] memory objectIds,
uint256[] memory amounts
) public virtual override {
for (uint256 i = 0; i < objectIds.length; i++) {
_burn(objectIds[i], amounts[i]);
}
emit TransferBatch(msg.sender, msg.sender, address(0), objectIds, amounts);
}
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
if(operator == _extensionAddress) {
return true;
}
return super.isApprovedForAll(account, operator);
}
function releaseExtension(bool keepMint) public override {
require(msg.sender == _extensionAddress, "Unauthorized Action!");
_keepMint = keepMint;
_extensionAddress = address(0);
}
function _isUnique(uint256 objectId) internal view returns (bool unique, uint256 unity, uint256 totalSupply, uint256 erc20Decimals) {
erc20Decimals = asERC20(objectId).decimals();
unity = erc20Decimals == 1 ? 1 : (10**erc20Decimals);
totalSupply = asERC20(objectId).totalSupply();
if(totalSupply == 0) {
unique = true;
} else {
unique = totalSupply <= unity;
}
}
} | * @dev Returns the name of the given token id @param objectId the id of the token whose name you want to know/ | function name(uint256 objectId)
public
virtual
override
view
returns (string memory)
{
return asERC20(objectId).name();
}
| 320,515 | [
1,
1356,
326,
508,
434,
326,
864,
1147,
612,
225,
18010,
326,
612,
434,
326,
1147,
8272,
508,
1846,
2545,
358,
5055,
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,
508,
12,
11890,
5034,
18010,
13,
203,
3639,
1071,
203,
3639,
5024,
203,
3639,
3849,
203,
3639,
1476,
203,
3639,
1135,
261,
1080,
3778,
13,
203,
565,
288,
203,
3639,
327,
487,
654,
39,
3462,
12,
1612,
548,
2934,
529,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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;
}
}
/**
* @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.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title 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 ERC223Interface
* @dev Simpler version of ERC223 interface
* @dev see https://github.com/ethereum/EIPs/issues/223
*/
contract ERC223Interface {
uint public totalSupply;
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public;
function transfer(address to, uint value, bytes data) public;
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
/**
* @title Contract that will work with ERC223 tokens.
*/
contract ERC223ReceivingContract {
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data) public;
}
/**
* @title Reference implementation of the ERC223 standard token.
*/
contract ERC223Token is ERC223Interface, Pausable {
using SafeMath for uint;
mapping(address => uint) balances; // List of user balances.
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) public whenNotPaused {
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value, _data);
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint _value) public whenNotPaused {
uint codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
emit Transfer(msg.sender, _to, _value, empty);
}
/**
* @dev Returns balance of the `_owner`.
*
* @param _owner The address whose balance will be returned.
* @return balance Balance of the `_owner`.
*/
function balanceOf(address _owner) public whenNotPaused constant returns (uint balance) {
return balances[_owner];
}
}
contract DskTokenMint is ERC223Token {
string public constant name = "DONSCOIN"; // Set the name for display purposes
string public constant symbol = "DSK"; // Set the symbol for display purposes
uint256 public constant decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public constant INITIAL_SUPPLY = 220000000000 * (10 ** uint256(decimals)); // Set the initial supply
uint256 public totalSupply = INITIAL_SUPPLY; // Set the total supply
uint256 internal Percent = INITIAL_SUPPLY.div(100); // Set the 1 percent of the total supply
uint256 public ICOSupply = Percent.mul(30); // Set the 30 percent of the ico supply
uint256 public DonscoinOwnerSupply = Percent.mul(50);
uint256 public DonscoinFreeSupply = Percent.mul(20);
address internal DonscoinOwner = 0x100eAc5b425C1e2527ee55ecdEF2EA2DfA4F904C; // Set a DonscoinOwner's address
address internal DonscoinFree = 0x026A175C90118a958E854E1972D72192459E4ED8; // Set a DonscoinFree's address
event InitSupply(uint256 owner, uint256 DonscoinOwner, uint256 DonscoinFree);
/**
* @dev The log is output when the contract is distributed.
*/
constructor() public {
emit InitSupply(ICOSupply, DonscoinOwnerSupply, DonscoinFreeSupply);
}
}
contract WhitelistedCrowdsale is Ownable {
mapping(address => bool) public whitelist;
event AddWhiteList(address who);
event DelWhiteList(address who);
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
emit AddWhiteList(_beneficiary);
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
emit DelWhiteList(_beneficiary);
}
}
/**
* @title DskCrowdSale
*/
contract DskCrowdSale is DskTokenMint, WhitelistedCrowdsale {
/**
* @dev Calculate date in seconds.
*/
uint constant Day = 60*60*24;
uint constant Month = 60*60*24*30;
uint constant SixMonth = 6 * Month;
uint constant Year = 12 * Month;
/**
* @dev Set sales start time and end time.
*/
uint public StartTime = 1548374400;
uint public EndTime = StartTime + SixMonth + 32400; // add +9:00
/**
* @dev Set private Sale EndTime and PreSale EndTime.
*/
uint public PrivateSaleEndTime = StartTime.add(Day * 50);
uint public PreSaleEndTime = PrivateSaleEndTime.add(Month*2);
/**
* @dev Flag value to check when SoftCapReached, HardCapReached, SaleClosed is achieved.
*/
bool public SoftCapReached = false;
bool public HardCapReached = false;
bool public SaleClosed = false;
bool private rentrancy_lock = false; // prevent certain functions from being recursively called
uint public constant Private_rate = 43875; // The ratio of DSK to Ether; 30% bonus
uint public constant Pre_rate = 38813; // The ratio of DSK to Ether; 15%
uint public constant Public = 35438; // The ratio of DSK to Ether; 5% bonus
uint public MinInvestMent = 2 * (10 ** decimals); // The minimum investment is 2 eth
uint public HardCap = 66000000000 * (10 ** uint256(decimals)); // Set hardcap number = 44000000000
uint public SoftCap = 2200000000 * (10 ** uint256(decimals)); // Set softcap number = 2200000000
/**
* @dev Check total quantity of total amount eth, sale amount DSK, refund amount.
*/
uint public TotalAmountETH;
uint public SaleAmountDSK;
uint public RefundAmount;
uint public InvestorNum; // check total inverstor number
/**
* @dev Providing information by inserting events into all functions.
*/
event SuccessCoreAccount(uint256 InvestorNum);
event Burn(address burner, uint256 value);
event SuccessInvestor(address RequestAddress, uint256 amount);
event SuccessSoftCap(uint256 SaleAmountDsk, uint256 time);
event SuccessHardCap(uint256 SaleAmountDsk, uint256 time);
event SucessWithdraw(address who, uint256 AmountEth, uint256 time);
event SuccessEthToOwner(address owner, uint256 AmountEth, uint256 time);
event dskTokenToInvestors(address InverstorAddress, uint256 Amount, uint256 now);
event dskTokenToCore(address CoreAddress, uint256 Amount, uint256 now);
event FailsafeWithdrawal(address InverstorAddress, uint256 Amount, uint256 now);
event FaildskTokenToInvestors(address InverstorAddress, uint256 Amount, uint256 now, uint256 ReleaseTime);
event FaildskTokenToCore(address CoreAddress, uint256 Amount, uint256 now, uint256 ReleaseTime);
event FailEthToOwner(address who, uint256 _amount, uint256 now);
event safeWithdrawalTry(address who);
/**
* @dev Check whether the specified time is satisfied.
*/
modifier beforeDeadline() { require (now < EndTime); _; }
modifier afterDeadline() { require (now >= EndTime); _; }
modifier afterStartTime() { require (now >= StartTime); _; }
modifier saleNotClosed() { require (!SaleClosed); _; }
/**
* @dev Prevent reentrant attacks.
*/
modifier nonReentrant() {
require(!rentrancy_lock);
rentrancy_lock = true;
_;
rentrancy_lock = false;
}
/**
* @dev Set investor structure.
*/
struct Investor {
uint256 EthAmount;
uint256 DskTokenAmount;
uint256 LockupTime;
bool DskTokenWithdraw;
}
mapping (address => Investor) public Inverstors; // Investor structure connector
mapping (uint256 => address) public InverstorList; // Investor list connector
constructor() public {
/**
* @dev Initial information setting of core members.
*/
Inverstors[DonscoinOwner].EthAmount = 0;
Inverstors[DonscoinOwner].LockupTime = EndTime;
Inverstors[DonscoinOwner].DskTokenAmount = DonscoinOwnerSupply;
Inverstors[DonscoinOwner].DskTokenWithdraw = false;
InverstorList[InvestorNum] = DonscoinOwner;
InvestorNum++;
Inverstors[DonscoinFree].EthAmount = 0;
Inverstors[DonscoinFree].LockupTime = StartTime;
Inverstors[DonscoinFree].DskTokenAmount = DonscoinFreeSupply;
Inverstors[DonscoinFree].DskTokenWithdraw = false;
InverstorList[InvestorNum] = DonscoinFree;
InvestorNum++;
emit SuccessCoreAccount(InvestorNum);
}
/**
* @dev It is automatically operated when depositing the eth.
* Set the minimum amount to a MinInvestMent
*/
function() payable public isWhitelisted(msg.sender) whenNotPaused beforeDeadline afterStartTime saleNotClosed nonReentrant {
require(msg.value >= MinInvestMent); // Check if minimum amount satisfies
uint amount = msg.value; // Assign investment amount
uint CurrentTime = now; // Assign Current time
address RequestAddress = msg.sender; // Investor address assignment
uint rate; // Token quantity variable
uint CurrentInvestMent = Inverstors[RequestAddress].EthAmount; // Allocated eth allocation so far
Inverstors[RequestAddress].EthAmount = CurrentInvestMent.add(amount); // Updated eth investment
Inverstors[RequestAddress].LockupTime = EndTime; // Set lockup time to trade tokens
Inverstors[RequestAddress].DskTokenWithdraw = false; // Confirm whether the token is withdrawn after unlocking
TotalAmountETH = TotalAmountETH.add(amount); // Total investment of all investors eth Quantity
/**
* @dev Bonus Quantity Variable Setting Logic
*/
if(CurrentTime<PrivateSaleEndTime) {
rate = Private_rate;
} else if(CurrentTime<PreSaleEndTime) {
rate = Pre_rate;
} else {
rate = Public;
}
uint NumDskToken = amount.mul(rate); // Dsk token Quantity assignment
ICOSupply = ICOSupply.sub(NumDskToken); // Decrease in ICOSupply quantity
if(ICOSupply > 0) {
// Update investor's lean token
Inverstors[RequestAddress].DskTokenAmount = Inverstors[RequestAddress].DskTokenAmount.add(NumDskToken);
SaleAmountDSK = SaleAmountDSK.add(NumDskToken); // Total amount of dsk tokens sold
CheckHardCap(); // Execute hard cap check function
CheckSoftCap(); // Execute soft cap check function
InverstorList[InvestorNum] = RequestAddress; // Assign the investor address to the current index
InvestorNum++; // Increase number of investors
emit SuccessInvestor(msg.sender, msg.value); // Investor Information event print
} else {
revert(); // If ICOSupply is less than 0, revert
}
}
/**
* @dev If it is a hard cap, set the flag to true and print the event
*/
function CheckHardCap() internal {
if (!HardCapReached) {
if (SaleAmountDSK >= HardCap) {
HardCapReached = true;
SaleClosed = true;
emit SuccessSoftCap(SaleAmountDSK, now);
}
}
}
/**
* @dev If it is a soft cap, set the flag to true and print the event
*/
function CheckSoftCap() internal {
if (!SoftCapReached) {
if (SaleAmountDSK >= SoftCap) {
SoftCapReached = true;
emit SuccessHardCap(SaleAmountDSK, now);
}
}
}
/**
* @dev If the soft cap fails, return the investment and print the event
*/
function safeWithdrawal() external afterDeadline nonReentrant {
if (!SoftCapReached) {
uint amount = Inverstors[msg.sender].EthAmount;
Inverstors[msg.sender].EthAmount = 0;
if (amount > 0) {
msg.sender.transfer(amount);
RefundAmount = RefundAmount.add(amount);
emit SucessWithdraw(msg.sender, amount, now);
} else {
emit FailsafeWithdrawal(msg.sender, amount, now);
}
} else {
emit safeWithdrawalTry(msg.sender);
}
}
/**
* @dev send owner's funds to the ICO owner - after ICO
*/
function transferEthToOwner(uint256 _amount) public onlyOwner afterDeadline nonReentrant {
if(SoftCapReached) {
owner.transfer(_amount);
emit SuccessEthToOwner(msg.sender, _amount, now);
} else {
emit FailEthToOwner(msg.sender, _amount, now);
}
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public onlyOwner afterDeadline nonReentrant {
require(_value <= ICOSupply);
address burner = msg.sender;
ICOSupply = ICOSupply.sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
}
function DskToOwner() public onlyOwner afterDeadline nonReentrant {
address RequestAddress = msg.sender;
Inverstors[RequestAddress].DskTokenAmount = Inverstors[RequestAddress].DskTokenAmount.add(ICOSupply);
ICOSupply = ICOSupply.sub(ICOSupply);
}
/**
* @dev After the lockout time, the tokens are paid to investors.
*/
function DskTokenToInvestors() public onlyOwner afterDeadline nonReentrant {
require(SoftCapReached);
for(uint256 i=2; i<InvestorNum; i++) {
uint256 ReleaseTime = Inverstors[InverstorList[i]].LockupTime;
address InverstorAddress = InverstorList[i];
uint256 Amount = Inverstors[InverstorAddress].DskTokenAmount;
if(now>ReleaseTime && Amount>0) {
balances[InverstorAddress] = balances[InverstorAddress] + Amount;
Inverstors[InverstorAddress].DskTokenAmount = Inverstors[InverstorAddress].DskTokenAmount.sub(Amount);
Inverstors[InverstorAddress].DskTokenWithdraw = true;
emit dskTokenToInvestors(InverstorAddress, Amount, now);
} else {
emit FaildskTokenToInvestors(InverstorAddress, Amount, now, ReleaseTime);
}
}
}
/**
* @dev After the lockout time, the tokens are paid to Core.
*/
function DskTokenToCore() public onlyOwner nonReentrant {
for(uint256 i=0; i<2; i++) {
uint256 ReleaseTime = Inverstors[InverstorList[i]].LockupTime;
address CoreAddress = InverstorList[i];
uint256 Amount = Inverstors[CoreAddress].DskTokenAmount;
if(now>ReleaseTime && Amount>0) {
balances[CoreAddress] = balances[CoreAddress] + Amount;
Inverstors[CoreAddress].DskTokenAmount = Inverstors[CoreAddress].DskTokenAmount.sub(Amount);
Inverstors[CoreAddress].DskTokenWithdraw = true;
emit dskTokenToCore(CoreAddress, Amount, now);
} else {
emit FaildskTokenToCore(CoreAddress, Amount, now, ReleaseTime);
}
}
}
} | Assign Current time
| uint CurrentTime = now; | 12,716,860 | [
1,
4910,
6562,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6562,
950,
273,
2037,
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
] |
./partial_match/1/0x312d25CAFdd6822C7B5dcdC8C7434E72f6E39C19/sources/FixedSupplyToken.sol | ------------------------------------------------------------------------ Transfer the balance from token owner's account to `to` account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------ | function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
| 9,212,066 | [
1,
29461,
12279,
326,
11013,
628,
1147,
3410,
1807,
2236,
358,
1375,
869,
68,
2236,
300,
16837,
1807,
2236,
1297,
1240,
18662,
11013,
358,
7412,
300,
374,
460,
29375,
854,
2935,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
7412,
12,
2867,
358,
16,
2254,
2430,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
324,
26488,
63,
3576,
18,
15330,
8009,
1717,
12,
7860,
1769,
203,
3639,
324,
26488,
63,
869,
65,
273,
324,
26488,
63,
869,
8009,
1289,
12,
7860,
1769,
203,
3639,
12279,
12,
3576,
18,
15330,
16,
358,
16,
2430,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
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
] |
./full_match/1/0x6fA5E1c43b5a466CBD1CAe7993B67C982400d481/sources/contracts/COIN.sol | exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract COINBOT is ERC20 {
using SafeMath for uint256;
bool private swapping;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public revShareAddress;
address public teamAddress;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapBackEnabled = false;
bool public banCapabilityRenounced = false;
mapping(address => bool) banned;
uint256 public tradingTotalFees;
uint256 public tradingRevShareFee;
uint256 public tradingLiquidityFee;
uint256 public tradingTeamFee;
uint256 public tokensForRevShare;
uint256 public tokensForLiquidity;
uint256 public tokensForTeam;
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
mapping(address => bool) public aMMPairs;
event SetAMMPair(address indexed pair, bool indexed value);
event revShareAddressUpdated(address indexed newAddress, address indexed oldAddress);
event teamAddressUpdated(address indexed newAddress, address indexed oldAddress);
event SwapToLP(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity);
pragma solidity 0.8.20;
import { SafeMath } from './libs/SafeMath.sol';
import { ERC20 } from './libs/ERC20.sol';
import { IUniswapV2Router02 } from './interfaces/IUniswapV2Router02.sol';
import { IUniswapV2Factory } from './interfaces/IUniswapV2Factory.sol';
import { IERC20 } from './interfaces/IERC20.sol';
constructor(address uniswapRouter) ERC20('CoinBot', 'COINBT') {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniswapRouter);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(
address(this),
_uniswapV2Router.WETH()
);
uint256 _tradingRevShareFee = 0;
uint256 _tradingLiquidityFee = 1;
uint256 _tradingTeamFee = 4;
uint256 totalSupply = 1_000_000 * 1e18;
tradingRevShareFee = _tradingRevShareFee;
tradingLiquidityFee = _tradingLiquidityFee;
tradingTeamFee = _tradingTeamFee;
tradingTotalFees = tradingRevShareFee + tradingLiquidityFee + tradingTeamFee;
revShareAddress = address(0x0185c185007a3099480a3D929944a805141C67CA);
_isExcludedMaxTransactionAmount[uniswapRouter] = true;
_isExcludedMaxTransactionAmount[uniswapV2Pair] = true;
_setAMMPair(address(uniswapV2Pair), true);
_excludeFromRules(owner());
_excludeFromRules(address(this));
_excludeFromRules(address(0xdead));
_mint(msg.sender, totalSupply);
}
receive() external payable {}
function enableTrading() external onlyOwner {
tradingActive = true;
swapBackEnabled = true;
}
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
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() * 5) / 1000) / 1e18,
'Cannot set maxTransactionAmount lower than 0.5%'
);
maxTransactionAmount = newNum * (10 ** 18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= ((totalSupply() * 10) / 1000) / 1e18, 'Cannot set maxWallet lower than 1.0%');
maxWallet = newNum * (10 ** 18);
}
function excludeFromFees(address _address, bool value) external onlyOwner {
require(limitsInEffect, 'Cannot grant privileges after limits have been removed.');
_isExcludedFromFees[_address] = value;
}
function excludeFromRules(address _address) external onlyOwner {
require(limitsInEffect, 'Cannot grant privileges after limits have been removed.');
_excludeFromRules(_address);
}
function _excludeFromRules(address _address) internal {
_isExcludedFromFees[_address] = true;
_isExcludedMaxTransactionAmount[_address] = true;
}
function updateTradingFees(
uint256 _revShareFee,
uint256 _liquidityFee,
uint256 _teamFee
) external onlyOwner {
tradingRevShareFee = _revShareFee;
tradingLiquidityFee = _liquidityFee;
tradingTeamFee = _teamFee;
tradingTotalFees = tradingRevShareFee + tradingLiquidityFee + tradingTeamFee;
require(tradingTeamFee <= tradingRevShareFee, 'teamFee cannot be greater than revShareFee.');
require(tradingTotalFees <= 5, 'Buy fees must be <= 5.');
}
function setAMMPair(address pair, bool value) external onlyOwner {
require(pair != uniswapV2Pair, 'The pair cannot be removed from aMMPairs');
_setAMMPair(pair, value);
}
function _setAMMPair(address pair, bool value) private {
aMMPairs[pair] = value;
_isExcludedMaxTransactionAmount[pair] = value;
emit SetAMMPair(pair, value);
}
function updateRevShareAddress(address newRevShareAddress) external onlyOwner {
emit revShareAddressUpdated(newRevShareAddress, revShareAddress);
_excludeFromRules(newRevShareAddress);
revShareAddress = newRevShareAddress;
}
function updateTeamAddress(address newAddress) external onlyOwner {
emit teamAddressUpdated(newAddress, teamAddress);
_excludeFromRules(newAddress);
teamAddress = newAddress;
}
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');
require(!banned[from], 'Sender banned');
require(!banned[to], 'Receiver banned');
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.');
}
if (aMMPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(
amount <= maxTransactionAmount,
'Buy transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
else if (aMMPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapBackEnabled &&
!swapping &&
!aMMPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if ((aMMPairs[to] || aMMPairs[from]) && tradingTotalFees > 0) {
fees = amount.mul(tradingTotalFees).div(100);
tokensForLiquidity += (fees * tradingLiquidityFee) / tradingTotalFees;
tokensForTeam += (fees * tradingTeamFee) / tradingTotalFees;
tokensForRevShare += (fees * tradingRevShareFee) / tradingTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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');
require(!banned[from], 'Sender banned');
require(!banned[to], 'Receiver banned');
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.');
}
if (aMMPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(
amount <= maxTransactionAmount,
'Buy transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
else if (aMMPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapBackEnabled &&
!swapping &&
!aMMPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if ((aMMPairs[to] || aMMPairs[from]) && tradingTotalFees > 0) {
fees = amount.mul(tradingTotalFees).div(100);
tokensForLiquidity += (fees * tradingLiquidityFee) / tradingTotalFees;
tokensForTeam += (fees * tradingTeamFee) / tradingTotalFees;
tokensForRevShare += (fees * tradingRevShareFee) / tradingTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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');
require(!banned[from], 'Sender banned');
require(!banned[to], 'Receiver banned');
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.');
}
if (aMMPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(
amount <= maxTransactionAmount,
'Buy transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
else if (aMMPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapBackEnabled &&
!swapping &&
!aMMPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if ((aMMPairs[to] || aMMPairs[from]) && tradingTotalFees > 0) {
fees = amount.mul(tradingTotalFees).div(100);
tokensForLiquidity += (fees * tradingLiquidityFee) / tradingTotalFees;
tokensForTeam += (fees * tradingTeamFee) / tradingTotalFees;
tokensForRevShare += (fees * tradingRevShareFee) / tradingTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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');
require(!banned[from], 'Sender banned');
require(!banned[to], 'Receiver banned');
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.');
}
if (aMMPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(
amount <= maxTransactionAmount,
'Buy transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
else if (aMMPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapBackEnabled &&
!swapping &&
!aMMPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if ((aMMPairs[to] || aMMPairs[from]) && tradingTotalFees > 0) {
fees = amount.mul(tradingTotalFees).div(100);
tokensForLiquidity += (fees * tradingLiquidityFee) / tradingTotalFees;
tokensForTeam += (fees * tradingTeamFee) / tradingTotalFees;
tokensForRevShare += (fees * tradingRevShareFee) / tradingTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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');
require(!banned[from], 'Sender banned');
require(!banned[to], 'Receiver banned');
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.');
}
if (aMMPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(
amount <= maxTransactionAmount,
'Buy transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
else if (aMMPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapBackEnabled &&
!swapping &&
!aMMPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if ((aMMPairs[to] || aMMPairs[from]) && tradingTotalFees > 0) {
fees = amount.mul(tradingTotalFees).div(100);
tokensForLiquidity += (fees * tradingLiquidityFee) / tradingTotalFees;
tokensForTeam += (fees * tradingTeamFee) / tradingTotalFees;
tokensForRevShare += (fees * tradingRevShareFee) / tradingTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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');
require(!banned[from], 'Sender banned');
require(!banned[to], 'Receiver banned');
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.');
}
if (aMMPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(
amount <= maxTransactionAmount,
'Buy transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
else if (aMMPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapBackEnabled &&
!swapping &&
!aMMPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if ((aMMPairs[to] || aMMPairs[from]) && tradingTotalFees > 0) {
fees = amount.mul(tradingTotalFees).div(100);
tokensForLiquidity += (fees * tradingLiquidityFee) / tradingTotalFees;
tokensForTeam += (fees * tradingTeamFee) / tradingTotalFees;
tokensForRevShare += (fees * tradingRevShareFee) / tradingTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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');
require(!banned[from], 'Sender banned');
require(!banned[to], 'Receiver banned');
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.');
}
if (aMMPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(
amount <= maxTransactionAmount,
'Buy transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
else if (aMMPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapBackEnabled &&
!swapping &&
!aMMPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if ((aMMPairs[to] || aMMPairs[from]) && tradingTotalFees > 0) {
fees = amount.mul(tradingTotalFees).div(100);
tokensForLiquidity += (fees * tradingLiquidityFee) / tradingTotalFees;
tokensForTeam += (fees * tradingTeamFee) / tradingTotalFees;
tokensForRevShare += (fees * tradingRevShareFee) / tradingTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
} else if (!_isExcludedMaxTransactionAmount[to]) {
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');
require(!banned[from], 'Sender banned');
require(!banned[to], 'Receiver banned');
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.');
}
if (aMMPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(
amount <= maxTransactionAmount,
'Buy transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
else if (aMMPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapBackEnabled &&
!swapping &&
!aMMPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if ((aMMPairs[to] || aMMPairs[from]) && tradingTotalFees > 0) {
fees = amount.mul(tradingTotalFees).div(100);
tokensForLiquidity += (fees * tradingLiquidityFee) / tradingTotalFees;
tokensForTeam += (fees * tradingTeamFee) / tradingTotalFees;
tokensForRevShare += (fees * tradingRevShareFee) / tradingTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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');
require(!banned[from], 'Sender banned');
require(!banned[to], 'Receiver banned');
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.');
}
if (aMMPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(
amount <= maxTransactionAmount,
'Buy transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
else if (aMMPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapBackEnabled &&
!swapping &&
!aMMPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if ((aMMPairs[to] || aMMPairs[from]) && tradingTotalFees > 0) {
fees = amount.mul(tradingTotalFees).div(100);
tokensForLiquidity += (fees * tradingLiquidityFee) / tradingTotalFees;
tokensForTeam += (fees * tradingTeamFee) / tradingTotalFees;
tokensForRevShare += (fees * tradingRevShareFee) / tradingTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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');
require(!banned[from], 'Sender banned');
require(!banned[to], 'Receiver banned');
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.');
}
if (aMMPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(
amount <= maxTransactionAmount,
'Buy transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
else if (aMMPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapBackEnabled &&
!swapping &&
!aMMPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if ((aMMPairs[to] || aMMPairs[from]) && tradingTotalFees > 0) {
fees = amount.mul(tradingTotalFees).div(100);
tokensForLiquidity += (fees * tradingLiquidityFee) / tradingTotalFees;
tokensForTeam += (fees * tradingTeamFee) / tradingTotalFees;
tokensForRevShare += (fees * tradingRevShareFee) / tradingTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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');
require(!banned[from], 'Sender banned');
require(!banned[to], 'Receiver banned');
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.');
}
if (aMMPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(
amount <= maxTransactionAmount,
'Buy transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
else if (aMMPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapBackEnabled &&
!swapping &&
!aMMPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if ((aMMPairs[to] || aMMPairs[from]) && tradingTotalFees > 0) {
fees = amount.mul(tradingTotalFees).div(100);
tokensForLiquidity += (fees * tradingLiquidityFee) / tradingTotalFees;
tokensForTeam += (fees * tradingTeamFee) / tradingTotalFees;
tokensForRevShare += (fees * tradingRevShareFee) / tradingTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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');
require(!banned[from], 'Sender banned');
require(!banned[to], 'Receiver banned');
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.');
}
if (aMMPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(
amount <= maxTransactionAmount,
'Buy transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
else if (aMMPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(
amount <= maxTransactionAmount,
'Sell transfer amount exceeds the maxTransactionAmount.'
);
require(amount + balanceOf(to) <= maxWallet, 'Max wallet exceeded');
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapBackEnabled &&
!swapping &&
!aMMPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if ((aMMPairs[to] || aMMPairs[from]) && tradingTotalFees > 0) {
fees = amount.mul(tradingTotalFees).div(100);
tokensForLiquidity += (fees * tradingLiquidityFee) / tradingTotalFees;
tokensForTeam += (fees * tradingTeamFee) / tradingTotalFees;
tokensForRevShare += (fees * tradingRevShareFee) / tradingTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
owner(),
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{ value: ethAmount }(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForRevShare + tokensForTeam;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForRevShare = ethBalance.mul(tokensForRevShare).div(
totalTokensToSwap - (tokensForLiquidity / 2)
);
uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(
totalTokensToSwap - (tokensForLiquidity / 2)
);
uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam;
tokensForLiquidity = 0;
tokensForRevShare = 0;
tokensForTeam = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapToLP(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForRevShare + tokensForTeam;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForRevShare = ethBalance.mul(tokensForRevShare).div(
totalTokensToSwap - (tokensForLiquidity / 2)
);
uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(
totalTokensToSwap - (tokensForLiquidity / 2)
);
uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam;
tokensForLiquidity = 0;
tokensForRevShare = 0;
tokensForTeam = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapToLP(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForRevShare + tokensForTeam;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForRevShare = ethBalance.mul(tokensForRevShare).div(
totalTokensToSwap - (tokensForLiquidity / 2)
);
uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(
totalTokensToSwap - (tokensForLiquidity / 2)
);
uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam;
tokensForLiquidity = 0;
tokensForRevShare = 0;
tokensForTeam = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapToLP(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2;
(success, ) = address(teamAddress).call{ value: ethForTeam }('');
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForRevShare + tokensForTeam;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForRevShare = ethBalance.mul(tokensForRevShare).div(
totalTokensToSwap - (tokensForLiquidity / 2)
);
uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(
totalTokensToSwap - (tokensForLiquidity / 2)
);
uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam;
tokensForLiquidity = 0;
tokensForRevShare = 0;
tokensForTeam = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapToLP(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
(success, ) = address(revShareAddress).call{ value: address(this).balance }('');
function withdrawStuckToken(address _token) external onlyOwner {
require(_token != address(0), '_token address cannot be 0');
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
IERC20(_token).transfer(teamAddress, _contractBalance);
}
function withdrawStuckEth() external onlyOwner {
require(success, 'Failed to withdraw ETH');
}
(bool success, ) = teamAddress.call{ value: address(this).balance }('');
function isBanned(address account) external view returns (bool) {
return banned[account];
}
function renounceBanCapability() external onlyOwner {
banCapabilityRenounced = true;
}
function ban(address _address) external onlyOwner {
require(!banCapabilityRenounced, 'Team has revoked ban rights');
require(
_address != address(uniswapV2Pair) &&
'Cannot ban Uniswap'
);
banned[_address] = true;
}
function unban(address _addr) external onlyOwner {
banned[_addr] = false;
}
}
| 3,061,941 | [
1,
10157,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
385,
6266,
38,
1974,
353,
4232,
39,
3462,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
225,
1426,
3238,
7720,
1382,
31,
203,
225,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
225,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
225,
1758,
1071,
5588,
9535,
1887,
31,
203,
225,
1758,
1071,
5927,
1887,
31,
203,
203,
225,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
225,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
225,
2254,
5034,
1071,
943,
16936,
31,
203,
203,
225,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
225,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
225,
1426,
1071,
7720,
2711,
1526,
273,
629,
31,
203,
203,
225,
1426,
1071,
25732,
17035,
16290,
27373,
273,
629,
31,
203,
225,
2874,
12,
2867,
516,
1426,
13,
324,
10041,
31,
203,
203,
225,
2254,
5034,
1071,
1284,
7459,
5269,
2954,
281,
31,
203,
225,
2254,
5034,
1071,
1284,
7459,
10070,
9535,
14667,
31,
203,
225,
2254,
5034,
1071,
1284,
7459,
48,
18988,
24237,
14667,
31,
203,
225,
2254,
5034,
1071,
1284,
7459,
8689,
14667,
31,
203,
203,
225,
2254,
5034,
1071,
2430,
1290,
10070,
9535,
31,
203,
225,
2254,
5034,
1071,
2430,
1290,
48,
18988,
24237,
31,
203,
225,
2254,
5034,
1071,
2430,
1290,
8689,
31,
203,
203,
225,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
2954,
281,
31,
203,
225,
2
] |
pragma solidity ^0.5.16;
import "./ERC721/ERC721Token.sol";
/**
* @title Repository of ERC721 Deeds
* This contract contains the list of deeds registered by users.
* This is a demo to show how tokens (deeds) can be minted and added
* to the repository.
*/
contract DeedRepository is ERC721Token {
/**
* @dev Created a DeedRepository with a name and symbol
* @param _name string represents the name of the repository
* @param _symbol string represents the symbol of the repository
*/
constructor(string memory _name, string memory _symbol)
public ERC721Token(_name, _symbol) {}
/**
* @dev Public function to register a new deed
* @dev Call the ERC721Token minter
* @param _tokenId uint256 represents a specific deed
* @param _uri string containing metadata/uri
*/
function registerDeed(uint256 _tokenId, string memory _uri) public {
_mint(msg.sender, _tokenId);
addDeedMetadata(_tokenId, _uri);
emit DeedRegistered(msg.sender, _tokenId);
}
/**
* @dev Public function to add metadata to a deed
* @param _tokenId represents a specific deed
* @param _uri text which describes the characteristics of a given deed
* @return whether the deed metadata was added to the repository
*/
function addDeedMetadata(uint256 _tokenId, string memory _uri) public returns(bool){
_setTokenURI(_tokenId, _uri);
return true;
}
/**
* @dev Event is triggered if deed/token is registered
* @param _by address of the registrar
* @param _tokenId uint256 represents a specific deed
*/
event DeedRegistered(address _by, uint256 _tokenId);
}
| * @title Repository of ERC721 Deeds This contract contains the list of deeds registered by users. This is a demo to show how tokens (deeds) can be minted and added to the repository./ | contract DeedRepository is ERC721Token {
constructor(string memory _name, string memory _symbol)
public ERC721Token(_name, _symbol) {}
function registerDeed(uint256 _tokenId, string memory _uri) public {
_mint(msg.sender, _tokenId);
addDeedMetadata(_tokenId, _uri);
emit DeedRegistered(msg.sender, _tokenId);
}
function addDeedMetadata(uint256 _tokenId, string memory _uri) public returns(bool){
_setTokenURI(_tokenId, _uri);
return true;
}
event DeedRegistered(address _by, uint256 _tokenId);
}
| 14,093,555 | [
1,
3305,
434,
4232,
39,
27,
5340,
1505,
9765,
1220,
6835,
1914,
326,
666,
434,
443,
9765,
4104,
635,
3677,
18,
1220,
353,
279,
21477,
358,
2405,
3661,
2430,
261,
323,
9765,
13,
848,
506,
312,
474,
329,
471,
3096,
358,
326,
3352,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
1505,
329,
3305,
353,
4232,
39,
27,
5340,
1345,
288,
203,
203,
203,
565,
3885,
12,
1080,
3778,
389,
529,
16,
533,
3778,
389,
7175,
13,
7010,
377,
203,
3639,
1071,
4232,
39,
27,
5340,
1345,
24899,
529,
16,
389,
7175,
13,
2618,
203,
565,
445,
1744,
758,
329,
12,
11890,
5034,
389,
2316,
548,
16,
533,
3778,
389,
1650,
13,
1071,
288,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
389,
2316,
548,
1769,
203,
3639,
527,
758,
329,
2277,
24899,
2316,
548,
16,
389,
1650,
1769,
203,
3639,
3626,
1505,
329,
10868,
12,
3576,
18,
15330,
16,
389,
2316,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
527,
758,
329,
2277,
12,
11890,
5034,
389,
2316,
548,
16,
533,
3778,
389,
1650,
13,
1071,
1135,
12,
6430,
15329,
203,
3639,
389,
542,
1345,
3098,
24899,
2316,
548,
16,
389,
1650,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
565,
871,
1505,
329,
10868,
12,
2867,
389,
1637,
16,
2254,
5034,
389,
2316,
548,
1769,
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
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract HappyNftFriendz is ERC721Enumerable, Ownable {
using Strings for uint256;
string public baseURI;
string public baseExtension = ".json";
string public notRevealedUri;
uint256 public cost;
// uint256 public maxSupply = 10420;
uint256 public maxSupply = 230;
// uint256 public maxInvestorsSupply = 100;
uint256 public maxInvestorsSupply = 2;
uint256 public maxMintAmount;
bool public paused = false;
bool public revealed = false;
bool public phase1 = false;
bool public phase2 = false;
bool public phase3 = false;
address[] public whitelistAddresses;
address[] public promoterzAddresses;
address[] public investorzList;
address[] public whitelistList;
address[] public promoterzList;
/**
** Community Address
*/
address private communityAddress = 0x0A098Eda01Ce92ff4A4CCb7A4fFFb5A43EBC70DC;
address private ownerFelipeFourTwenty;
address private ownerZentennial;
address private ownerFarama;
address private ownerValDev;
address private ownerShared;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri,
address _ownerFelipeFourTwenty,
address _ownerZentennial,
address _ownerFarama,
address _ownerValDev,
address _ownerShared
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
internalMint(100, address(this));
internalMint(5, _ownerFelipeFourTwenty);
internalMint(5, _ownerZentennial);
internalMint(5, _ownerFarama);
internalMint(5, _ownerValDev);
setOwnerAddress(_ownerFelipeFourTwenty, "ownerFelipeFourTwenty");
setOwnerAddress(_ownerZentennial, "ownerZentennial");
setOwnerAddress(_ownerFarama, "ownerFarama");
setOwnerAddress(_ownerValDev, "ownerValDev");
setOwnerAddress(_ownerShared, "ownerShared");
}
// public
function mint( uint256 _mintAmount) public payable {
require(!paused, "The contract is paused");
uint256 supply = totalSupply();
require(_mintAmount > 0, "Need to mint at least 1 NFT");
require(supply + _mintAmount <= maxSupply, "Sold Out!");
if (phase1) {
require(investorzList.length + _mintAmount <= maxInvestorsSupply, "Investorz sold out!");
require(_mintAmount <= maxMintAmount, "Max mint amount per session exceeded");
uint256 ownerTokenCount = balanceOf(msg.sender);
require(ownerTokenCount < maxMintAmount, "Max mint amount per Address exceeded");
require(msg.value >= cost * _mintAmount, "Insufficient funds");
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
investorzList.push(msg.sender);
} else if (phase2) {
if (isPromoter(msg.sender) == true) {
require(_mintAmount <= 1 , "Promoter only can mint 1");
require(msg.value >= 0 ether * _mintAmount, "Insufficient funds");
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
promoterzList.push(msg.sender);
removePromoter(msg.sender);
} else if (isWhitelisted(msg.sender) == true) {
uint promotersCount = _getUserPromotersCount(msg.sender);
uint investorsCount = _getUserInvestorsCount(msg.sender);
uint userNftCount = promotersCount + investorsCount;
uint256 ownerTokenCount = balanceOf(msg.sender);
uint256 totalTokenAmountAddress = ownerTokenCount + _mintAmount - userNftCount;
require(totalTokenAmountAddress <= maxMintAmount, "Max mint amount per Address exceeded");
require(msg.value >= cost * _mintAmount, "Insufficient funds");
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
whitelistList.push(msg.sender);
} else {
require(isWhitelisted(msg.sender) == true, "No Promoter nor whitelisted");
}
} else if (phase3) {
uint promotersCount = _getUserPromotersCount(msg.sender);
uint whiteListCount = _getUserWhitelistCount(msg.sender);
uint investorsCount = _getUserInvestorsCount(msg.sender);
uint userNftCount = promotersCount + whiteListCount + investorsCount;
uint256 ownerTokenCount = balanceOf(msg.sender);
uint256 totalTokenAmountAddress = ownerTokenCount + _mintAmount - userNftCount;
require(totalTokenAmountAddress <= maxMintAmount, "Max mint amount per Address exceeded");
require(msg.value >= cost * _mintAmount, "Insufficient funds");
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
} else {
require(phase3, "No Phase Activated");
}
}
/**
** Function to ACTIVATE phrase 1
*/
function activatePhrase1(uint256 _newCost, uint256 _newMaxMintAmount) public onlyOwner {
setCost(_newCost);
setMaxMintAmount(_newMaxMintAmount);
phase1 = true;
phase2 = false;
phase3 = false;
}
/**
** Function to ACTIVATE phrase 2
*/
function activatePhrase2(uint256 _newCost, uint256 _newMaxMintAmount) public onlyOwner {
setCost(_newCost);
setMaxMintAmount(_newMaxMintAmount);
phase1 = false;
phase2 = true;
phase3 = false;
}
/**
** Function to ACTIVATE phrase 3
*/
function activatePhrase3(uint256 _newCost, uint256 _newMaxMintAmount) public onlyOwner {
setCost(_newCost);
setMaxMintAmount(_newMaxMintAmount);
phase1 = false;
phase2 = false;
phase3 = true;
}
/**
** Function to SET owner address
*/
function setOwnerAddress(address _address, string memory _owner) public onlyOwner {
if(keccak256(abi.encodePacked(_owner)) == keccak256(abi.encodePacked("ownerFelipeFourTwenty"))) {
ownerFelipeFourTwenty = _address;
} else if(keccak256(abi.encodePacked(_owner)) == keccak256(abi.encodePacked("ownerZentennial"))) {
ownerZentennial = _address;
} else if(keccak256(abi.encodePacked(_owner)) == keccak256(abi.encodePacked("ownerFarama"))) {
ownerFarama = _address;
} else if(keccak256(abi.encodePacked(_owner)) == keccak256(abi.encodePacked("ownerValDev"))) {
ownerValDev = _address;
} else if(keccak256(abi.encodePacked(_owner)) == keccak256(abi.encodePacked("ownerShared"))) {
ownerShared = _address;
}
}
/**
** Function to GET owner address
*/
function _getOwnerAddress(string memory _owner) internal view virtual returns (address accepted) {
if(keccak256(abi.encodePacked(_owner)) == keccak256(abi.encodePacked("ownerFelipeFourTwenty"))) {
return ownerFelipeFourTwenty;
} else if(keccak256(abi.encodePacked(_owner)) == keccak256(abi.encodePacked("ownerZentennial"))) {
return ownerZentennial;
} else if(keccak256(abi.encodePacked(_owner)) == keccak256(abi.encodePacked("ownerFarama"))) {
return ownerFarama;
} else if(keccak256(abi.encodePacked(_owner)) == keccak256(abi.encodePacked("ownerValDev"))) {
return ownerValDev;
} else if(keccak256(abi.encodePacked(_owner)) == keccak256(abi.encodePacked("ownerShared"))) {
return ownerShared;
}
}
/**
** Function to SET BaseURI
*/
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
/**
** Function to GET BaseURI
*/
function _getBaseURI() internal view virtual returns (string memory) {
return baseURI;
}
/**
** Function to SET Reveal
*/
function setReveal(bool _reveal) public onlyOwner {
revealed = _reveal;
}
/**
** Function to GET Reveal
*/
function _getReveal() internal view virtual returns (bool accepted) {
return revealed;
}
/**
** Function to SET Cost
*/
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
/**
** Function to GET Cost
*/
function _getCost() internal view virtual returns (uint256 accepted) {
return cost;
}
/**
** Function to SET NotRevealedURI
*/
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
/**
** Function to GET Cost
*/
function _getNotRevealedURI() internal view virtual returns (string memory) {
return notRevealedUri;
}
/**
** Function to SET WhitelistUses
*/
function setWhitelistUsers(address[] calldata _users) public onlyOwner {
delete whitelistAddresses;
whitelistAddresses = _users;
}
/**
** Function to GET WhitelistUses
*/
function _getWhitelistUsers() internal view virtual returns (address[] storage) {
return whitelistAddresses;
}
/**
** Function to SET PromoterUsers
*/
function setPromoterUsers(address[] calldata _users) public onlyOwner {
delete promoterzAddresses;
promoterzAddresses = _users;
}
/**
** Function to GET PromoterUsers
*/
function _getPromoterUsers() internal view virtual returns (address[] storage) {
return promoterzAddresses;
}
/**
** Function to SET MaxMintAmount
*/
function setMaxMintAmount(uint256 _newMaxMintAmount) public onlyOwner {
maxMintAmount = _newMaxMintAmount;
}
/**
** Function to GET MaxMintAmount
*/
function _getMaxMintAmount() internal view virtual returns (uint256) {
return maxMintAmount;
}
/**
** Function to SET BaseExtension
*/
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
/**
** Function to GET BaseExtension
*/
function _getBaseExtension() internal view virtual returns (string memory) {
return baseExtension;
}
/**
** Function to SET project status
*/
function setPause(bool _state) public onlyOwner {
paused = _state;
}
/**
** Function to CHECK if user is whitelisted
*/
function isWhitelisted (address _user) internal view returns (bool) {
for(uint256 i = 0; i < whitelistAddresses.length; i++) {
if(whitelistAddresses[i] == _user) {
return true;
}
}
return false;
}
/**
** Function to GET user whitelist count
*/
function _getUserWhitelistCount (address _user) internal view returns (uint) {
uint count = 0;
for(uint256 i = 0; i < whitelistList.length; i++) {
if(whitelistList[i] == _user) {
count++;
}
}
return count;
}
/**
** Function to GET user promoters list count
*/
function _getUserPromotersCount (address _user) internal view returns (uint) {
uint count = 0;
for(uint256 i = 0; i < promoterzList.length; i++) {
if(promoterzList[i] == _user) {
count++;
}
}
return count;
}
/**
** Function to GET user investorz list count
*/
function _getUserInvestorsCount (address _user) internal view returns (uint) {
uint count = 0;
for(uint256 i = 0; i < investorzList.length; i++) {
if(investorzList[i] == _user) {
count++;
}
}
return count;
}
/**
** Function to CHECK if user is promoter
*/
function isPromoter (address _user) internal view returns (bool) {
for(uint256 i = 0; i < promoterzAddresses.length; i++) {
if(promoterzAddresses[i] == _user) {
return true;
}
}
return false;
}
/**
** Function to REMOVE address from promoters list
*/
function removePromoter (address _user) internal {
for(uint256 i = 0; i < promoterzAddresses.length; i++) {
if(promoterzAddresses[i] == _user) {
delete promoterzAddresses[i];
}
}
}
/**
** Function to GET tokens of address
*/
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
/**
** Function to GET token URI of a tokenId.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
/**
** Function to WITHDRAW funds
*/
function withdraw() public payable onlyOwner {
uint256 fiftyPercent = address(this).balance * 50 / 100;
uint256 fifthPart = fiftyPercent * 20 / 100;
(bool hs1, ) = payable(ownerFelipeFourTwenty).call{value: fifthPart}("");
require(hs1);
(bool hs2, ) = payable(ownerFarama).call{value: fifthPart}("");
require(hs2);
(bool hs3, ) = payable(ownerValDev).call{value: fifthPart}("");
require(hs3);
(bool hs4, ) = payable(ownerZentennial).call{value: fifthPart}("");
require(hs4);
(bool hs5, ) = payable(ownerShared).call{value: fifthPart}("");
require(hs5);
(bool os, ) = payable(communityAddress).call{value: address(this).balance}("");
require(os);
}
/**
** Function to mint internally funds
*/
function internalMint( uint256 _mintAmount, address _ownerAddress) public onlyOwner payable {
require(!paused, "The contract is paused");
uint256 supply = totalSupply();
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_ownerAddress, supply + i);
}
}
/**
** Function to GET totalSupply
*/
function _getTotalSupply() internal view virtual returns (uint256 accepted) {
uint256 supply = totalSupply();
return supply;
}
}
| * Function to REMOVE address from promoters list/ | function removePromoter (address _user) internal {
for(uint256 i = 0; i < promoterzAddresses.length; i++) {
if(promoterzAddresses[i] == _user) {
delete promoterzAddresses[i];
}
}
}
| 12,803,864 | [
1,
2083,
358,
26056,
1758,
628,
3012,
352,
414,
666,
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,
225,
445,
1206,
13224,
20005,
261,
2867,
389,
1355,
13,
2713,
288,
203,
1377,
364,
12,
11890,
5034,
277,
273,
374,
31,
277,
411,
3012,
20005,
94,
7148,
18,
2469,
31,
277,
27245,
288,
203,
1850,
309,
12,
17401,
20005,
94,
7148,
63,
77,
65,
422,
389,
1355,
13,
288,
203,
2868,
1430,
3012,
20005,
94,
7148,
63,
77,
15533,
203,
1850,
289,
203,
1377,
289,
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
] |
./full_match/43113/0xf0f8d1C714Df54CD71336fB9db024f71a5214e0D/sources/project_/contracts/Pmm.sol | setFirstAddressInternal(user); set first address ????? tis(referral); | function join(address referral) public payable nonReentrant {
require(referrerOfUser[referral] != address(0), "referral not join");
address user = msg.sender;
uint256 _amount = msg.value;
require(identityOfUser[user] == 0, "had joined");
require(_amount == allAmount, "amount error");
_recordReferral(user,referral);
setSerialNumber(user);
seePointReward(referral);
bossReward(referral);
poolReward();
paiw(referral);
}
| 7,137,866 | [
1,
542,
3759,
1887,
3061,
12,
1355,
1769,
444,
1122,
1758,
225,
5317,
14646,
35,
268,
291,
12,
1734,
29084,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
1233,
12,
2867,
1278,
29084,
13,
1071,
8843,
429,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
1734,
11110,
951,
1299,
63,
1734,
29084,
65,
480,
1758,
12,
20,
3631,
315,
1734,
29084,
486,
1233,
8863,
203,
3639,
1758,
729,
273,
1234,
18,
15330,
31,
203,
3639,
2254,
5034,
389,
8949,
273,
1234,
18,
1132,
31,
203,
3639,
2583,
12,
10781,
951,
1299,
63,
1355,
65,
422,
374,
16,
315,
76,
361,
12114,
8863,
203,
3639,
2583,
24899,
8949,
422,
777,
6275,
16,
315,
8949,
555,
8863,
203,
203,
3639,
389,
3366,
1957,
29084,
12,
1355,
16,
1734,
29084,
1769,
203,
3639,
444,
6342,
1854,
12,
1355,
1769,
203,
203,
203,
3639,
2621,
2148,
17631,
1060,
12,
1734,
29084,
1769,
203,
3639,
324,
8464,
17631,
1060,
12,
1734,
29084,
1769,
203,
3639,
2845,
17631,
1060,
5621,
203,
203,
203,
3639,
6790,
22315,
12,
1734,
29084,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.